From dd43d6f88a4139fad7a0ed798a62509e0fa449ef Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 12:34:05 +0100 Subject: [PATCH 1/9] cleanup --- costs/src/context.rs | 16 +- grovedb-version/src/lib.rs | 10 +- .../src/version/grovedb_versions.rs | 2 + grovedb-version/src/version/v1.rs | 2 + .../estimated_costs/average_case_costs.rs | 8 +- .../batch/estimated_costs/worst_case_costs.rs | 6 +- .../batch/just_in_time_reference_update.rs | 14 +- grovedb/src/batch/mod.rs | 462 +++------- grovedb/src/debugger.rs | 21 +- grovedb/src/element/delete.rs | 2 - grovedb/src/element/exists.rs | 4 +- grovedb/src/element/get.rs | 86 +- grovedb/src/element/helpers.rs | 2 +- grovedb/src/element/insert.rs | 236 +++++- grovedb/src/element/mod.rs | 1 - grovedb/src/element/query.rs | 342 ++++---- grovedb/src/element/serialize.rs | 2 +- grovedb/src/error.rs | 8 +- .../src/estimated_costs/average_case_costs.rs | 28 +- .../src/estimated_costs/worst_case_costs.rs | 19 +- grovedb/src/lib.rs | 482 ++--------- grovedb/src/merk_cache.rs | 266 ++++++ grovedb/src/operations/auxiliary.rs | 116 +-- grovedb/src/operations/delete/average_case.rs | 10 +- .../src/operations/delete/delete_up_tree.rs | 6 +- grovedb/src/operations/delete/mod.rs | 479 +++-------- grovedb/src/operations/delete/worst_case.rs | 10 +- grovedb/src/operations/get/average_case.rs | 2 +- grovedb/src/operations/get/mod.rs | 179 +--- grovedb/src/operations/get/query.rs | 37 +- grovedb/src/operations/get/worst_case.rs | 2 +- grovedb/src/operations/insert/mod.rs | 367 ++------ grovedb/src/operations/is_empty_tree.rs | 30 +- grovedb/src/operations/proof/generate.rs | 23 +- grovedb/src/operations/proof/verify.rs | 3 +- grovedb/src/query/mod.rs | 2 +- grovedb/src/reference_path.rs | 551 +++++++++++- grovedb/src/replication.rs | 157 ++-- grovedb/src/tests/mod.rs | 91 +- grovedb/src/tests/sum_tree_tests.rs | 84 +- grovedb/src/tests/tree_hashes_tests.rs | 22 +- grovedb/src/util.rs | 790 +++++++----------- grovedb/src/visualize.rs | 64 +- merk/src/merk/meta.rs | 111 +++ merk/src/merk/mod.rs | 56 +- merk/src/merk/open.rs | 26 +- merk/src/merk/restore.rs | 14 +- merk/src/proofs/tree.rs | 22 +- merk/src/test_utils/mod.rs | 10 +- merk/src/test_utils/temp_merk.rs | 44 +- merk/src/tree/encoding.rs | 2 +- merk/src/tree/mod.rs | 10 +- merk/src/tree/ops.rs | 6 +- merk/src/tree/walk/mod.rs | 8 +- path/Cargo.toml | 2 + path/src/subtree_path.rs | 132 ++- path/src/subtree_path_builder.rs | 100 ++- path/src/util/compact_bytes.rs | 46 +- path/src/util/cow_like.rs | 2 +- storage/src/rocksdb_storage.rs | 2 +- storage/src/rocksdb_storage/storage.rs | 49 +- .../src/rocksdb_storage/storage_context.rs | 2 - .../storage_context/context_no_tx.rs | 286 ------- storage/src/rocksdb_storage/tests.rs | 32 +- storage/src/storage.rs | 91 +- 65 files changed, 2944 insertions(+), 3153 deletions(-) create mode 100644 grovedb/src/merk_cache.rs create mode 100644 merk/src/merk/meta.rs delete mode 100644 storage/src/rocksdb_storage/storage_context/context_no_tx.rs diff --git a/costs/src/context.rs b/costs/src/context.rs index d69cb054e..8224cb888 100644 --- a/costs/src/context.rs +++ b/costs/src/context.rs @@ -116,6 +116,15 @@ impl CostResult { pub fn cost_as_result(self) -> Result { self.value.map(|_| self.cost) } + + /// Call the provided function on success without altering result or cost. + pub fn for_ok(self, f: impl FnOnce(&T)) -> CostResult { + if let Ok(x) = &self.value { + f(x) + } + + self + } } impl CostResult, E> { @@ -170,8 +179,9 @@ impl CostsExt for T {} /// 1. Early termination on error; /// 2. Because of 1, `Result` is removed from the equation; /// 3. `CostContext` is removed too because it is added to external cost -/// accumulator; 4. Early termination uses external cost accumulator so previous -/// costs won't be lost. +/// accumulator; +/// 4. Early termination uses external cost accumulator so previous costs won't +/// be lost. #[macro_export] macro_rules! cost_return_on_error { ( &mut $cost:ident, $($body:tt)+ ) => { @@ -193,7 +203,7 @@ macro_rules! cost_return_on_error { /// so no costs will be added except previously accumulated. #[macro_export] macro_rules! cost_return_on_error_no_add { - ( &$cost:ident, $($body:tt)+ ) => { + ( $cost:ident, $($body:tt)+ ) => { { use $crate::CostsExt; let result = { $($body)+ }; diff --git a/grovedb-version/src/lib.rs b/grovedb-version/src/lib.rs index 48b80a52e..ca2bf9b9c 100644 --- a/grovedb-version/src/lib.rs +++ b/grovedb-version/src/lib.rs @@ -1,4 +1,4 @@ -use crate::version::GroveVersion; +use version::GroveVersion; pub mod error; pub mod version; @@ -8,7 +8,7 @@ macro_rules! check_grovedb_v0_with_cost { ($method:expr, $version:expr) => {{ const EXPECTED_VERSION: u16 = 0; if $version != EXPECTED_VERSION { - return Err(GroveVersionError::UnknownVersionMismatch { + return Err($crate::error::GroveVersionError::UnknownVersionMismatch { method: $method.to_string(), known_versions: vec![EXPECTED_VERSION], received: $version, @@ -24,7 +24,7 @@ macro_rules! check_grovedb_v0 { ($method:expr, $version:expr) => {{ const EXPECTED_VERSION: u16 = 0; if $version != EXPECTED_VERSION { - return Err(GroveVersionError::UnknownVersionMismatch { + return Err($crate::error::GroveVersionError::UnknownVersionMismatch { method: $method.to_string(), known_versions: vec![EXPECTED_VERSION], received: $version, @@ -39,7 +39,7 @@ macro_rules! check_merk_v0_with_cost { ($method:expr, $version:expr) => {{ const EXPECTED_VERSION: u16 = 0; if $version != EXPECTED_VERSION { - return Err(GroveVersionError::UnknownVersionMismatch { + return Err($crate::error::GroveVersionError::UnknownVersionMismatch { method: $method.to_string(), known_versions: vec![EXPECTED_VERSION], received: $version, @@ -55,7 +55,7 @@ macro_rules! check_merk_v0 { ($method:expr, $version:expr) => {{ const EXPECTED_VERSION: u16 = 0; if $version != EXPECTED_VERSION { - return Err(GroveVersionError::UnknownVersionMismatch { + return Err($crate::error::GroveVersionError::UnknownVersionMismatch { method: $method.to_string(), known_versions: vec![EXPECTED_VERSION], received: $version, diff --git a/grovedb-version/src/version/grovedb_versions.rs b/grovedb-version/src/version/grovedb_versions.rs index 598fa1789..cc52e6199 100644 --- a/grovedb-version/src/version/grovedb_versions.rs +++ b/grovedb-version/src/version/grovedb_versions.rs @@ -48,6 +48,7 @@ pub struct GroveDBOperationsGetVersions { pub get: FeatureVersion, pub get_caching_optional: FeatureVersion, pub follow_reference: FeatureVersion, + pub follow_reference_once: FeatureVersion, pub get_raw: FeatureVersion, pub get_raw_caching_optional: FeatureVersion, pub get_raw_optional: FeatureVersion, @@ -190,6 +191,7 @@ pub struct GroveDBElementMethodVersions { pub get_optional_from_storage: FeatureVersion, pub get_with_absolute_refs: FeatureVersion, pub get_value_hash: FeatureVersion, + pub get_with_value_hash: FeatureVersion, pub get_specialized_cost: FeatureVersion, pub value_defined_cost: FeatureVersion, pub value_defined_cost_for_serialized_value: FeatureVersion, diff --git a/grovedb-version/src/version/v1.rs b/grovedb-version/src/version/v1.rs index 97cfb38b3..b6245e561 100644 --- a/grovedb-version/src/version/v1.rs +++ b/grovedb-version/src/version/v1.rs @@ -39,6 +39,7 @@ pub const GROVE_V1: GroveVersion = GroveVersion { get_optional_from_storage: 0, get_with_absolute_refs: 0, get_value_hash: 0, + get_with_value_hash: 0, get_specialized_cost: 0, value_defined_cost: 0, value_defined_cost_for_serialized_value: 0, @@ -71,6 +72,7 @@ pub const GROVE_V1: GroveVersion = GroveVersion { get: 0, get_caching_optional: 0, follow_reference: 0, + follow_reference_once: 0, get_raw: 0, get_raw_caching_optional: 0, get_raw_optional: 0, diff --git a/grovedb/src/batch/estimated_costs/average_case_costs.rs b/grovedb/src/batch/estimated_costs/average_case_costs.rs index ef64b0f4d..c7bbbc056 100644 --- a/grovedb/src/batch/estimated_costs/average_case_costs.rs +++ b/grovedb/src/batch/estimated_costs/average_case_costs.rs @@ -196,7 +196,7 @@ impl TreeCache for AverageCaseTreeCacheKnownPaths { let mut cost = OperationCost::default(); let layer_element_estimates = cost_return_on_error_no_add!( - &cost, + cost, self.paths.get(path).ok_or_else(|| { let paths = self .paths @@ -218,7 +218,7 @@ impl TreeCache for AverageCaseTreeCacheKnownPaths { // Then we have to get the tree if self.cached_merks.get(path).is_none() { let layer_info = cost_return_on_error_no_add!( - &cost, + cost, self.paths.get(path).ok_or_else(|| { let paths = self .paths @@ -233,7 +233,7 @@ impl TreeCache for AverageCaseTreeCacheKnownPaths { }) ); cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_average_case_get_merk_at_path::( &mut cost, path, @@ -272,7 +272,7 @@ impl TreeCache for AverageCaseTreeCacheKnownPaths { // Then we have to get the tree if !self.cached_merks.contains_key(&base_path) { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_average_case_get_merk_at_path::( &mut cost, &base_path, diff --git a/grovedb/src/batch/estimated_costs/worst_case_costs.rs b/grovedb/src/batch/estimated_costs/worst_case_costs.rs index 9bf9a808b..37cc74b12 100644 --- a/grovedb/src/batch/estimated_costs/worst_case_costs.rs +++ b/grovedb/src/batch/estimated_costs/worst_case_costs.rs @@ -192,7 +192,7 @@ impl TreeCache for WorstCaseTreeCacheKnownPaths { let mut cost = OperationCost::default(); let worst_case_layer_element_estimates = cost_return_on_error_no_add!( - &cost, + cost, self.paths .get(path) .ok_or_else(|| Error::PathNotFoundInCacheForEstimatedCosts(format!( @@ -204,7 +204,7 @@ impl TreeCache for WorstCaseTreeCacheKnownPaths { // Then we have to get the tree if !self.cached_merks.contains(path) { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_worst_case_get_merk_at_path::( &mut cost, path, @@ -247,7 +247,7 @@ impl TreeCache for WorstCaseTreeCacheKnownPaths { // Then we have to get the tree if !self.cached_merks.contains(&base_path) { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_worst_case_get_merk_at_path::( &mut cost, &base_path, diff --git a/grovedb/src/batch/just_in_time_reference_update.rs b/grovedb/src/batch/just_in_time_reference_update.rs index f4385b899..c52b3cc40 100644 --- a/grovedb/src/batch/just_in_time_reference_update.rs +++ b/grovedb/src/batch/just_in_time_reference_update.rs @@ -53,7 +53,7 @@ where updated_new_element_with_old_flags.set_flags(maybe_old_flags.clone()); // There are no storage flags, we can just hash new element let new_serialized_bytes = cost_return_on_error_no_add!( - &cost, + cost, updated_new_element_with_old_flags.serialize(grove_version) ); let val_hash = value_hash(&new_serialized_bytes).unwrap_add_cost(&mut cost); @@ -93,7 +93,7 @@ where updated_new_element_with_old_flags.set_flags(maybe_old_flags.clone()); let serialized_with_old_flags = cost_return_on_error_no_add!( - &cost, + cost, updated_new_element_with_old_flags.serialize(grove_version) ); KV::node_value_byte_cost_size( @@ -115,7 +115,7 @@ where if let Some(old_element_flags) = maybe_old_flags.as_mut() { if let BasicStorageRemoval(removed_bytes) = storage_costs.removed_bytes { let (_, value_removed_bytes) = cost_return_on_error_no_add!( - &cost, + cost, split_removal_bytes(old_element_flags, 0, removed_bytes) ); storage_costs.removed_bytes = value_removed_bytes; @@ -125,7 +125,7 @@ where let mut new_element_cloned = original_new_element.clone(); let changed = cost_return_on_error_no_add!( - &cost, + cost, (flags_update)( &storage_costs, maybe_old_flags.clone(), @@ -145,10 +145,8 @@ where return Ok(val_hash).wrap_with_cost(cost); } else { // There are no storage flags, we can just hash new element - let new_serialized_bytes = cost_return_on_error_no_add!( - &cost, - new_element_cloned.serialize(grove_version) - ); + let new_serialized_bytes = + cost_return_on_error_no_add!(cost, new_element_cloned.serialize(grove_version)); new_storage_cost = KV::node_value_byte_cost_size( key.len() as u32, diff --git a/grovedb/src/batch/mod.rs b/grovedb/src/batch/mod.rs index 2767ab2b1..be7a570db 100644 --- a/grovedb/src/batch/mod.rs +++ b/grovedb/src/batch/mod.rs @@ -57,12 +57,9 @@ use grovedb_merk::{ }; use grovedb_path::SubtreePath; use grovedb_storage::{ - rocksdb_storage::{PrefixedRocksDbStorageContext, PrefixedRocksDbTransactionContext}, - Storage, StorageBatch, StorageContext, -}; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, + rocksdb_storage::PrefixedRocksDbTransactionContext, Storage, StorageBatch, StorageContext, }; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use grovedb_visualize::{Drawer, Visualize}; use integer_encoding::VarInt; use itertools::Itertools; @@ -79,6 +76,7 @@ use crate::{ reference_path::{ path_from_reference_path_type, path_from_reference_qualified_path_type, ReferencePathType, }, + util::TxRef, Element, ElementFlags, Error, GroveDb, Transaction, TransactionArg, }; @@ -816,7 +814,7 @@ where Ok(referenced_element_value_hash).wrap_with_cost(cost) } else if let Some(referenced_path) = intermediate_reference_info { let path = cost_return_on_error_no_add!( - &cost, + cost, path_from_reference_qualified_path_type(referenced_path.clone(), qualified_path) ); self.follow_reference_get_value_hash( @@ -909,7 +907,7 @@ where if let Some(referenced_element) = referenced_element { let element = cost_return_on_error_no_add!( - &cost, + cost, Element::deserialize(referenced_element.as_slice(), grove_version).map_err(|_| { Error::CorruptedData(String::from("unable to deserialize element")) }) @@ -1009,13 +1007,13 @@ where match element { Element::Item(..) | Element::SumItem(..) => { let serialized = - cost_return_on_error_no_add!(&cost, element.serialize(grove_version)); + cost_return_on_error_no_add!(cost, element.serialize(grove_version)); let val_hash = value_hash(&serialized).unwrap_add_cost(&mut cost); Ok(val_hash).wrap_with_cost(cost) } Element::Reference(path, ..) => { let path = cost_return_on_error_no_add!( - &cost, + cost, path_from_reference_qualified_path_type(path, qualified_path) ); self.follow_reference_get_value_hash( @@ -1083,7 +1081,7 @@ where match element { Element::Item(..) | Element::SumItem(..) => { let serialized = cost_return_on_error_no_add!( - &cost, + cost, element.serialize(grove_version) ); if element.get_flags().is_none() { @@ -1130,7 +1128,7 @@ where } Element::Reference(path, ..) => { let path = cost_return_on_error_no_add!( - &cost, + cost, path_from_reference_qualified_path_type( path.clone(), qualified_path @@ -1156,13 +1154,13 @@ where GroveOp::InsertOnly { element } => match element { Element::Item(..) | Element::SumItem(..) => { let serialized = - cost_return_on_error_no_add!(&cost, element.serialize(grove_version)); + cost_return_on_error_no_add!(cost, element.serialize(grove_version)); let val_hash = value_hash(&serialized).unwrap_add_cost(&mut cost); Ok(val_hash).wrap_with_cost(cost) } Element::Reference(path, ..) => { let path = cost_return_on_error_no_add!( - &cost, + cost, path_from_reference_qualified_path_type(path.clone(), qualified_path) ); self.follow_reference_get_value_hash( @@ -1436,7 +1434,7 @@ where ) ); cost_return_on_error_no_add!( - &cost, + cost, Element::deserialize(value.as_slice(), grove_version).map_err(|_| { Error::CorruptedData(String::from("unable to deserialize element")) }) @@ -1564,7 +1562,7 @@ where ), }; let merk_feature_type = - cost_return_on_error_no_add!(&cost, element.get_feature_type(is_sum_tree)); + cost_return_on_error_no_add!(cost, element.get_feature_type(is_sum_tree)); cost_return_on_error!( &mut cost, @@ -1761,7 +1759,7 @@ impl GroveDb { if batch_apply_options.base_root_storage_is_free { // the base root is free let mut update_root_cost = cost_return_on_error_no_add!( - &cost, + cost, merk_tree_cache .update_base_merk_root_key(calculated_root_key, grove_version) .cost_as_result() @@ -2217,74 +2215,6 @@ impl GroveDb { } } - /// Opens merk at path with given storage batch context. Returns CostResult. - pub fn open_batch_merk_at_path<'a, B: AsRef<[u8]>>( - &'a self, - storage_batch: &'a StorageBatch, - path: SubtreePath, - new_merk: bool, - grove_version: &GroveVersion, - ) -> CostResult, Error> { - check_grovedb_v0_with_cost!( - "open_batch_merk_at_path", - grove_version - .grovedb_versions - .apply_batch - .open_batch_merk_at_path - ); - let mut local_cost = OperationCost::default(); - let storage = self - .db - .get_storage_context(path.clone(), Some(storage_batch)) - .unwrap_add_cost(&mut local_cost); - - if new_merk { - let merk_type = if path.is_root() { - MerkType::BaseMerk - } else { - MerkType::LayeredMerk - }; - Ok(Merk::open_empty(storage, merk_type, false)).wrap_with_cost(local_cost) - } else if let Some((base_path, last)) = path.derive_parent() { - let parent_storage = self - .db - .get_storage_context(base_path, Some(storage_batch)) - .unwrap_add_cost(&mut local_cost); - let element = cost_return_on_error!( - &mut local_cost, - Element::get_from_storage(&parent_storage, last, grove_version) - ); - let is_sum_tree = element.is_sum_tree(); - if let Element::Tree(root_key, _) | Element::SumTree(root_key, ..) = element { - Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version, - ) - .map_err(|_| { - Error::CorruptedData("cannot open a subtree with given root key".to_owned()) - }) - .add_cost(local_cost) - } else { - Err(Error::CorruptedData( - "cannot open a subtree as parent exists but is not a tree".to_owned(), - )) - .wrap_with_cost(local_cost) - } - } else { - Merk::open_base( - storage, - false, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version, - ) - .map_err(|_| Error::CorruptedData("cannot open a subtree".to_owned())) - .add_cost(local_cost) - } - } - /// Applies batch of operations on GroveDB pub fn apply_batch_with_element_flags_update( &self, @@ -2319,6 +2249,8 @@ impl GroveDb { return Ok(()).wrap_with_cost(cost); } + let tx = TxRef::new(&self.db, transaction); + // Determines whether to check batch operation consistency // return false if the disable option is set to true, returns true for any other // case @@ -2351,93 +2283,49 @@ impl GroveDb { // 5. Remove operation from the tree, repeat until there are operations to do; // 6. Add root leaves save operation to the batch // 7. Apply storage_cost batch - if let Some(tx) = transaction { - cost_return_on_error!( - &mut cost, - self.apply_body( - ops, - batch_apply_options, - update_element_flags_function, - split_removal_bytes_function, - |path, new_merk| { - self.open_batch_transactional_merk_at_path( - &storage_batch, - path.into(), - tx, - new_merk, - grove_version, - ) - }, - grove_version - ) - ); - - // TODO: compute batch costs - cost_return_on_error!( - &mut cost, - self.db - .commit_multi_context_batch(storage_batch, Some(tx)) - .map_err(|e| e.into()) - ); - - // Keep this commented for easy debugging in the future. - // let issues = self - // .visualize_verify_grovedb(Some(tx), true, - // &Default::default()) .unwrap(); - // if issues.len() > 0 { - // println!( - // "tx_issues: {}", - // issues - // .iter() - // .map(|(hash, (a, b, c))| format!("{}: {} {} {}", - // hash, a, b, c)) .collect::>() - // .join(" | ") - // ); - // } - } else { - cost_return_on_error!( - &mut cost, - self.apply_body( - ops, - batch_apply_options, - update_element_flags_function, - split_removal_bytes_function, - |path, new_merk| { - self.open_batch_merk_at_path( - &storage_batch, - path.into(), - new_merk, - grove_version, - ) - }, - grove_version - ) - ); + cost_return_on_error!( + &mut cost, + self.apply_body( + ops, + batch_apply_options, + update_element_flags_function, + split_removal_bytes_function, + |path, new_merk| { + self.open_batch_transactional_merk_at_path( + &storage_batch, + path.into(), + tx.as_ref(), + new_merk, + grove_version, + ) + }, + grove_version + ) + ); - // TODO: compute batch costs - cost_return_on_error!( - &mut cost, - self.db - .commit_multi_context_batch(storage_batch, None) - .map_err(|e| e.into()) - ); + // TODO: compute batch costs + cost_return_on_error!( + &mut cost, + self.db + .commit_multi_context_batch(storage_batch, Some(tx.as_ref())) + .map_err(|e| e.into()) + ); - // Keep this commented for easy debugging in the future. - // let issues = self - // .visualize_verify_grovedb(None, true, &Default::default()) - // .unwrap(); - // if issues.len() > 0 { - // println!( - // "non_tx_issues: {}", - // issues - // .iter() - // .map(|(hash, (a, b, c))| format!("{}: {} {} {}", - // hash, a, b, c)) .collect::>() - // .join(" | ") - // ); - // } - } - Ok(()).wrap_with_cost(cost) + // Keep this commented for easy debugging in the future. + // let issues = self + // .visualize_verify_grovedb(Some(tx), true, + // &Default::default()) .unwrap(); + // if issues.len() > 0 { + // println!( + // "tx_issues: {}", + // issues + // .iter() + // .map(|(hash, (a, b, c))| format!("{}: {} {} {}", + // hash, a, b, c)) .collect::>() + // .join(" | ") + // ); + // } + tx.commit_local().wrap_with_cost(cost) } /// Applies a partial batch of operations on GroveDB @@ -2481,6 +2369,8 @@ impl GroveDb { return Ok(()).wrap_with_cost(cost); } + let tx = TxRef::new(&self.db, transaction); + let mut batch_apply_options = batch_apply_options.unwrap_or_default(); if batch_apply_options.batch_pause_height.is_none() { // we default to pausing at the root tree, which is the most common case @@ -2517,177 +2407,93 @@ impl GroveDb { // 5. Remove operation from the tree, repeat until there are operations to do; // 6. Add root leaves save operation to the batch // 7. Apply storage_cost batch - if let Some(tx) = transaction { - let left_over_operations = cost_return_on_error!( - &mut cost, - self.apply_body( - ops, - Some(batch_apply_options.clone()), - &mut update_element_flags_function, - &mut split_removal_bytes_function, - |path, new_merk| { - self.open_batch_transactional_merk_at_path( - &storage_batch, - path.into(), - tx, - new_merk, - grove_version, - ) - }, - grove_version - ) - ); - // if we paused at the root height, the left over operations would be to replace - // a lot of leaf nodes in the root tree - - // let's build the write batch - let (mut write_batch, mut pending_costs) = cost_return_on_error!( - &mut cost, - self.db - .build_write_batch(storage_batch) - .map_err(|e| e.into()) - ); - - let total_current_costs = cost.clone().add(pending_costs.clone()); - - // todo: estimate root costs - - // at this point we need to send the pending costs back - // we will get GroveDB a new set of GroveDBOps - - let new_operations = cost_return_on_error_no_add!( - &cost, - add_on_operations(&total_current_costs, &left_over_operations) - ); - - // we are trying to finalize - batch_apply_options.batch_pause_height = None; - - let continue_storage_batch = StorageBatch::new(); - - cost_return_on_error!( - &mut cost, - self.continue_partial_apply_body( - left_over_operations, - new_operations, - Some(batch_apply_options), - update_element_flags_function, - split_removal_bytes_function, - |path, new_merk| { - self.open_batch_transactional_merk_at_path( - &continue_storage_batch, - path.into(), - tx, - new_merk, - grove_version, - ) - }, - grove_version - ) - ); - - // let's build the write batch - let continued_pending_costs = cost_return_on_error!( - &mut cost, - self.db - .continue_write_batch(&mut write_batch, continue_storage_batch) - .map_err(|e| e.into()) - ); - - pending_costs.add_assign(continued_pending_costs); + let left_over_operations = cost_return_on_error!( + &mut cost, + self.apply_body( + ops, + Some(batch_apply_options.clone()), + &mut update_element_flags_function, + &mut split_removal_bytes_function, + |path, new_merk| { + self.open_batch_transactional_merk_at_path( + &storage_batch, + path.into(), + tx.as_ref(), + new_merk, + grove_version, + ) + }, + grove_version + ) + ); + // if we paused at the root height, the left over operations would be to replace + // a lot of leaf nodes in the root tree - // TODO: compute batch costs - cost_return_on_error!( - &mut cost, - self.db - .commit_db_write_batch(write_batch, pending_costs, Some(tx)) - .map_err(|e| e.into()) - ); - } else { - let left_over_operations = cost_return_on_error!( - &mut cost, - self.apply_body( - ops, - Some(batch_apply_options.clone()), - &mut update_element_flags_function, - &mut split_removal_bytes_function, - |path, new_merk| { - self.open_batch_merk_at_path( - &storage_batch, - path.into(), - new_merk, - grove_version, - ) - }, - grove_version - ) - ); + // let's build the write batch + let (mut write_batch, mut pending_costs) = cost_return_on_error!( + &mut cost, + self.db + .build_write_batch(storage_batch) + .map_err(|e| e.into()) + ); - // if we paused at the root height, the left over operations would be to replace - // a lot of leaf nodes in the root tree + let total_current_costs = cost.clone().add(pending_costs.clone()); - // let's build the write batch - let (mut write_batch, mut pending_costs) = cost_return_on_error!( - &mut cost, - self.db - .build_write_batch(storage_batch) - .map_err(|e| e.into()) - ); + // todo: estimate root costs - let total_current_costs = cost.clone().add(pending_costs.clone()); + // at this point we need to send the pending costs back + // we will get GroveDB a new set of GroveDBOps - // at this point we need to send the pending costs back - // we will get GroveDB a new set of GroveDBOps + let new_operations = cost_return_on_error_no_add!( + cost, + add_on_operations(&total_current_costs, &left_over_operations) + ); - let new_operations = cost_return_on_error_no_add!( - &cost, - add_on_operations(&total_current_costs, &left_over_operations) - ); + // we are trying to finalize + batch_apply_options.batch_pause_height = None; - // we are trying to finalize - batch_apply_options.batch_pause_height = None; + let continue_storage_batch = StorageBatch::new(); - let continue_storage_batch = StorageBatch::new(); + cost_return_on_error!( + &mut cost, + self.continue_partial_apply_body( + left_over_operations, + new_operations, + Some(batch_apply_options), + update_element_flags_function, + split_removal_bytes_function, + |path, new_merk| { + self.open_batch_transactional_merk_at_path( + &continue_storage_batch, + path.into(), + tx.as_ref(), + new_merk, + grove_version, + ) + }, + grove_version + ) + ); - cost_return_on_error!( - &mut cost, - self.continue_partial_apply_body( - left_over_operations, - new_operations, - Some(batch_apply_options), - update_element_flags_function, - split_removal_bytes_function, - |path, new_merk| { - self.open_batch_merk_at_path( - &continue_storage_batch, - path.into(), - new_merk, - grove_version, - ) - }, - grove_version - ) - ); + // let's build the write batch + let continued_pending_costs = cost_return_on_error!( + &mut cost, + self.db + .continue_write_batch(&mut write_batch, continue_storage_batch) + .map_err(|e| e.into()) + ); - // let's build the write batch - let continued_pending_costs = cost_return_on_error!( - &mut cost, - self.db - .continue_write_batch(&mut write_batch, continue_storage_batch) - .map_err(|e| e.into()) - ); + pending_costs.add_assign(continued_pending_costs); - pending_costs.add_assign(continued_pending_costs); + // TODO: compute batch costs + cost_return_on_error!( + &mut cost, + self.db + .commit_db_write_batch(write_batch, pending_costs, Some(tx.as_ref())) + .map_err(|e| e.into()) + ); - // TODO: compute batch costs - cost_return_on_error!( - &mut cost, - self.db - .commit_db_write_batch(write_batch, pending_costs, None) - .map_err(|e| e.into()) - ); - } - Ok(()).wrap_with_cost(cost) + tx.commit_local().wrap_with_cost(cost) } #[cfg(feature = "estimated_costs")] diff --git a/grovedb/src/debugger.rs b/grovedb/src/debugger.rs index 1920ff813..7475dbbf4 100644 --- a/grovedb/src/debugger.rs +++ b/grovedb/src/debugger.rs @@ -35,7 +35,7 @@ use crate::{ operations::proof::{GroveDBProof, LayerProof, ProveOptions}, query_result_type::{QueryResultElement, QueryResultElements, QueryResultType}, reference_path::ReferencePathType, - GroveDb, + GroveDb, Transaction, }; const GROVEDBG_ZIP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/grovedbg.zip")); @@ -227,9 +227,10 @@ async fn fetch_node( }): Json>, ) -> Result>, AppError> { let db = state.get_snapshot(session_id).await?; + let tx = db.start_transaction(); let merk = db - .open_non_transactional_merk_at_path(path.as_slice().into(), None, GroveVersion::latest()) + .open_transactional_merk_at_path(path.as_slice().into(), &tx, None, GroveVersion::latest()) .unwrap()?; let node = merk.get_node_dbg(&key)?; @@ -249,9 +250,10 @@ async fn fetch_root_node( }): Json>, ) -> Result>, AppError> { let db = state.get_snapshot(session_id).await?; + let tx = db.start_transaction(); let merk = db - .open_non_transactional_merk_at_path(SubtreePath::empty(), None, GroveVersion::latest()) + .open_transactional_merk_at_path(SubtreePath::empty(), &tx, None, GroveVersion::latest()) .unwrap()?; let node = merk.get_root_node_dbg()?; @@ -289,6 +291,7 @@ async fn fetch_with_path_query( }): Json>, ) -> Result>, AppError> { let db = state.get_snapshot(session_id).await?; + let tx = db.start_transaction(); let path_query = path_query_to_grovedb(json_path_query); @@ -299,16 +302,21 @@ async fn fetch_with_path_query( true, false, QueryResultType::QueryPathKeyElementTrioResultType, - None, + Some(&tx), GroveVersion::latest(), ) .unwrap()? .0; - Ok(Json(query_result_to_grovedbg(&db, grovedb_query_result)?)) + Ok(Json(query_result_to_grovedbg( + &db, + &tx, + grovedb_query_result, + )?)) } fn query_result_to_grovedbg( db: &GroveDb, + tx: &Transaction, query_result: QueryResultElements, ) -> Result, crate::Error> { let mut result = Vec::new(); @@ -322,8 +330,9 @@ fn query_result_to_grovedbg( _ => { last_merk = Some(( path.clone(), - db.open_non_transactional_merk_at_path( + db.open_transactional_merk_at_path( path.as_slice().into(), + &tx, None, GroveVersion::latest(), ) diff --git a/grovedb/src/element/delete.rs b/grovedb/src/element/delete.rs index ced24e273..f4e196dba 100644 --- a/grovedb/src/element/delete.rs +++ b/grovedb/src/element/delete.rs @@ -12,8 +12,6 @@ use grovedb_storage::StorageContext; #[cfg(feature = "full")] use grovedb_version::check_grovedb_v0_with_cost; #[cfg(feature = "full")] -use grovedb_version::error::GroveVersionError; -#[cfg(feature = "full")] use grovedb_version::version::GroveVersion; #[cfg(feature = "full")] diff --git a/grovedb/src/element/exists.rs b/grovedb/src/element/exists.rs index 63dcfe4bd..b57d5c5c7 100644 --- a/grovedb/src/element/exists.rs +++ b/grovedb/src/element/exists.rs @@ -4,9 +4,7 @@ use grovedb_costs::{CostResult, CostsExt, OperationCost}; use grovedb_merk::Merk; use grovedb_storage::StorageContext; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use crate::{Element, Error}; diff --git a/grovedb/src/element/get.rs b/grovedb/src/element/get.rs index ded859d36..bd904fb77 100644 --- a/grovedb/src/element/get.rs +++ b/grovedb/src/element/get.rs @@ -1,28 +1,24 @@ //! Get //! Implements functions in Element for getting -#[cfg(feature = "full")] use grovedb_costs::{ cost_return_on_error, cost_return_on_error_no_add, CostResult, CostsExt, OperationCost, }; -use grovedb_merk::tree::kv::KV; -#[cfg(feature = "full")] -use grovedb_merk::Merk; -#[cfg(feature = "full")] -use grovedb_merk::{ed::Decode, tree::TreeNodeInner}; -#[cfg(feature = "full")] -use grovedb_storage::StorageContext; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, +use grovedb_merk::{ + ed::Decode, + tree::{kv::KV, TreeNodeInner}, + Merk, }; +use grovedb_storage::StorageContext; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use integer_encoding::VarInt; -use crate::element::{SUM_ITEM_COST_SIZE, SUM_TREE_COST_SIZE, TREE_COST_SIZE}; -#[cfg(feature = "full")] -use crate::{Element, Error, Hash}; +use crate::{ + element::{SUM_ITEM_COST_SIZE, SUM_TREE_COST_SIZE, TREE_COST_SIZE}, + Element, Error, Hash, +}; impl Element { - #[cfg(feature = "full")] /// Get an element from Merk under a key; path should be resolved and proper /// Merk should be loaded by this moment pub fn get<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( @@ -47,7 +43,6 @@ impl Element { }) } - #[cfg(feature = "full")] /// Get an element from Merk under a key; path should be resolved and proper /// Merk should be loaded by this moment pub fn get_optional<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( @@ -73,7 +68,7 @@ impl Element { .map_err(|e| Error::CorruptedData(e.to_string())) ); let element = cost_return_on_error_no_add!( - &cost, + cost, value_opt .map(|value| { Self::deserialize(value.as_slice(), grove_version).map_err(|_| { @@ -86,7 +81,6 @@ impl Element { Ok(element).wrap_with_cost(cost) } - #[cfg(feature = "full")] /// Get an element directly from storage under a key /// Merk does not need to be loaded /// Errors if element doesn't exist @@ -110,7 +104,6 @@ impl Element { }) } - #[cfg(feature = "full")] /// Get an element directly from storage under a key /// Merk does not need to be loaded pub fn get_optional_from_storage<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( @@ -134,7 +127,7 @@ impl Element { .map_err(|e| Error::CorruptedData(e.to_string())) ); let maybe_tree_inner: Option = cost_return_on_error_no_add!( - &cost, + cost, node_value_opt .map(|node_value| { Decode::decode(node_value.as_slice()) @@ -145,7 +138,7 @@ impl Element { let value = maybe_tree_inner.map(|tree_inner| tree_inner.value_as_owned()); let element = cost_return_on_error_no_add!( - &cost, + cost, value .as_ref() .map(|value| { @@ -198,7 +191,6 @@ impl Element { Ok(element).wrap_with_cost(cost) } - #[cfg(feature = "full")] /// Get an element from Merk under a key; path should be resolved and proper /// Merk should be loaded by this moment pub fn get_with_absolute_refs<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( @@ -223,14 +215,13 @@ impl Element { ); let absolute_element = cost_return_on_error_no_add!( - &cost, + cost, element.convert_if_reference_to_absolute_reference(path, Some(key.as_ref())) ); Ok(absolute_element).wrap_with_cost(cost) } - #[cfg(feature = "full")] /// Get an element's value hash from Merk under a key pub fn get_value_hash<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( merk: &Merk, @@ -257,9 +248,48 @@ impl Element { Ok(value_hash).wrap_with_cost(cost) } + + /// Get an element and its value hash from Merk under a key + pub fn get_with_value_hash<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( + merk: &Merk, + key: K, + allow_cache: bool, + grove_version: &GroveVersion, + ) -> CostResult<(Element, Hash), Error> { + check_grovedb_v0_with_cost!( + "get_with_value_hash", + grove_version.grovedb_versions.element.get_with_value_hash + ); + let mut cost = OperationCost::default(); + + let Some((value, value_hash)) = cost_return_on_error!( + &mut cost, + merk.get_value_and_value_hash( + key.as_ref(), + allow_cache, + Some(&Element::value_defined_cost_for_serialized_value), + grove_version + ) + .map_err(|e| Error::CorruptedData(e.to_string())) + ) else { + return Err(Error::PathKeyNotFound(format!( + "get: key \"{}\" not found in Merk that has a root key [{}] and is of type {}", + hex::encode(key), + merk.root_key() + .map(hex::encode) + .unwrap_or("None".to_string()), + merk.merk_type + ))) + .wrap_with_cost(cost); + }; + + Self::deserialize(value.as_slice(), grove_version) + .map_err(|_| Error::CorruptedData(String::from("unable to deserialize element"))) + .map(|e| (e, value_hash)) + .wrap_with_cost(cost) + } } -#[cfg(feature = "full")] #[cfg(test)] mod tests { use grovedb_path::SubtreePath; @@ -272,8 +302,10 @@ mod tests { let grove_version = GroveVersion::latest(); let storage = TempStorage::new(); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); + let ctx = storage - .get_storage_context(SubtreePath::empty(), Some(&batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), &tx) .unwrap(); let mut merk = Merk::open_base( ctx, @@ -293,12 +325,12 @@ mod tests { .expect("expected successful insertion 2"); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .unwrap(); let ctx = storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(); let mut merk = Merk::open_base( ctx, diff --git a/grovedb/src/element/helpers.rs b/grovedb/src/element/helpers.rs index 5b3662dff..2ca87cd06 100644 --- a/grovedb/src/element/helpers.rs +++ b/grovedb/src/element/helpers.rs @@ -13,7 +13,7 @@ use grovedb_merk::{ TreeFeatureType::{BasicMerkNode, SummedMerkNode}, }; #[cfg(feature = "full")] -use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; +use grovedb_version::{check_grovedb_v0, version::GroveVersion}; #[cfg(feature = "full")] use integer_encoding::VarInt; diff --git a/grovedb/src/element/insert.rs b/grovedb/src/element/insert.rs index ce0144a2b..9f75e1d2f 100644 --- a/grovedb/src/element/insert.rs +++ b/grovedb/src/element/insert.rs @@ -7,13 +7,23 @@ use grovedb_costs::{ }; use grovedb_merk::{BatchEntry, Error as MerkError, Merk, MerkOptions, Op, TreeFeatureType}; use grovedb_storage::StorageContext; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use integer_encoding::VarInt; use crate::{Element, Element::SumItem, Error, Hash}; +#[derive(Debug)] +pub struct Delta<'e> { + pub new: &'e Element, + pub old: Option, +} + +impl Delta<'_> { + pub(crate) fn has_changed(&self) -> bool { + self.old.as_ref().map(|o| o != self.new).unwrap_or(true) + } +} + impl Element { #[cfg(feature = "full")] /// Insert an element in Merk under a key; path should be resolved and @@ -191,19 +201,14 @@ impl Element { #[cfg(feature = "full")] /// Insert an element in Merk under a key if the value is different from - /// what already exists; path should be resolved and proper Merk should - /// be loaded by this moment If transaction is not passed, the batch - /// will be written immediately. If transaction is passed, the operation - /// will be committed on the transaction commit. - /// The bool represents if we indeed inserted. - /// If the value changed we return the old element. + /// what already exists, returning delta. pub fn insert_if_changed_value<'db, S: StorageContext<'db>>( &self, merk: &mut Merk, key: &[u8], options: Option, grove_version: &GroveVersion, - ) -> CostResult<(bool, Option), Error> { + ) -> CostResult { check_grovedb_v0_with_cost!( "insert_if_changed_value", grove_version @@ -215,18 +220,18 @@ impl Element { let mut cost = OperationCost::default(); let previous_element = cost_return_on_error!( &mut cost, - Self::get_optional_from_storage(&merk.storage, key, grove_version) + Self::get_optional(&merk, key, true, grove_version) ); - let needs_insert = match &previous_element { - None => true, - Some(previous_element) => previous_element != self, + let delta = Delta { + new: self, + old: previous_element, }; - if !needs_insert { - Ok((false, None)).wrap_with_cost(cost) - } else { + + if delta.has_changed() { cost_return_on_error!(&mut cost, self.insert(merk, key, options, grove_version)); - Ok((true, previous_element)).wrap_with_cost(cost) } + + Ok(delta).wrap_with_cost(cost) } #[cfg(feature = "full")] @@ -280,11 +285,7 @@ impl Element { } #[cfg(feature = "full")] - /// Insert a reference element in Merk under a key; path should be resolved - /// and proper Merk should be loaded by this moment - /// If transaction is not passed, the batch will be written immediately. - /// If transaction is passed, the operation will be committed on the - /// transaction commit. + /// Insert a reference element in Merk under a key. pub fn insert_reference<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( &self, merk: &mut Merk, @@ -329,6 +330,74 @@ impl Element { .map_err(|e| Error::CorruptedData(e.to_string())) } + #[cfg(feature = "full")] + /// Insert a reference element in Merk under a key returning a delta. + pub fn insert_reference_if_changed_value<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( + &self, + merk: &mut Merk, + key: K, + referenced_value: Hash, + options: Option, + grove_version: &GroveVersion, + ) -> CostResult { + check_grovedb_v0_with_cost!( + "insert_reference", + grove_version.grovedb_versions.element.insert_reference + ); + + let serialized = match self.serialize(grove_version) { + Ok(s) => s, + Err(e) => return Err(e).wrap_with_cost(Default::default()), + }; + + let mut cost = OperationCost::default(); + + let previous_element = cost_return_on_error!( + &mut cost, + Self::get_optional(&merk, &key, true, grove_version) + ); + let delta = Delta { + new: self, + old: previous_element, + }; + + if delta.has_changed() { + let merk_feature_type = cost_return_on_error!( + &mut cost, + self.get_feature_type(merk.is_sum_tree) + .wrap_with_cost(OperationCost::default()) + ); + + let batch_operations = [( + key, + Op::PutCombinedReference(serialized, referenced_value, merk_feature_type), + )]; + let uses_sum_nodes = merk.is_sum_tree; + cost_return_on_error!( + &mut cost, + merk.apply_with_specialized_costs::<_, Vec>( + &batch_operations, + &[], + options, + &|key, value| { + Self::specialized_costs_for_key_value( + key, + value, + uses_sum_nodes, + grove_version, + ) + .map_err(|e| MerkError::ClientCorruptionError(e.to_string())) + }, + Some(&Element::value_defined_cost_for_serialized_value), + grove_version, + ) + .map_err(|e| Error::CorruptedData(e.to_string())) + ); + } + + Ok(delta).wrap_with_cost(cost) + } + #[cfg(feature = "full")] /// Adds a "Put" op to batch operations with reference and key. Returns /// CostResult. @@ -362,11 +431,7 @@ impl Element { } #[cfg(feature = "full")] - /// Insert a tree element in Merk under a key; path should be resolved - /// and proper Merk should be loaded by this moment - /// If transaction is not passed, the batch will be written immediately. - /// If transaction is passed, the operation will be committed on the - /// transaction commit. + /// Insert a tree element in Merk under a key. pub fn insert_subtree<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( &self, merk: &mut Merk, @@ -387,10 +452,10 @@ impl Element { let cost = OperationCost::default(); let merk_feature_type = - cost_return_on_error_no_add!(&cost, self.get_feature_type(merk.is_sum_tree)); + cost_return_on_error_no_add!(cost, self.get_feature_type(merk.is_sum_tree)); let tree_cost = - cost_return_on_error_no_add!(&cost, self.get_specialized_cost(grove_version)); + cost_return_on_error_no_add!(cost, self.get_specialized_cost(grove_version)); let cost = tree_cost + self.get_flags().as_ref().map_or(0, |flags| { @@ -416,6 +481,85 @@ impl Element { .map_err(|e| Error::CorruptedData(e.to_string())) } + #[cfg(feature = "full")] + /// Insert a tree element in Merk under a key, returning delta. + pub fn insert_subtree_if_changed<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( + &self, + merk: &mut Merk, + key: K, + subtree_root_hash: Hash, + options: Option, + grove_version: &GroveVersion, + ) -> CostResult { + check_grovedb_v0_with_cost!( + "insert_subtree", + grove_version.grovedb_versions.element.insert_subtree + ); + + let serialized = match self.serialize(grove_version) { + Ok(s) => s, + Err(e) => return Err(e).wrap_with_cost(Default::default()), + }; + + let mut cost = OperationCost::default(); + + let previous_element = cost_return_on_error!( + &mut cost, + Self::get_optional(&merk, &key, true, grove_version) + ); + + let delta = Delta { + new: self, + old: previous_element, + }; + + if delta.has_changed() { + let merk_feature_type = + cost_return_on_error_no_add!(cost, self.get_feature_type(merk.is_sum_tree)); + + let tree_cost = + cost_return_on_error_no_add!(cost, self.get_specialized_cost(grove_version)); + + let specialized_cost = tree_cost + + self.get_flags().as_ref().map_or(0, |flags| { + let flags_len = flags.len() as u32; + flags_len + flags_len.required_space() as u32 + }); + let batch_operations = [( + key, + Op::PutLayeredReference( + serialized, + specialized_cost, + subtree_root_hash, + merk_feature_type, + ), + )]; + let uses_sum_nodes = merk.is_sum_tree; + cost_return_on_error!( + &mut cost, + merk.apply_with_specialized_costs::<_, Vec>( + &batch_operations, + &[], + options, + &|key, value| { + Self::specialized_costs_for_key_value( + key, + value, + uses_sum_nodes, + grove_version, + ) + .map_err(|e| MerkError::ClientCorruptionError(e.to_string())) + }, + Some(&Element::value_defined_cost_for_serialized_value), + grove_version, + ) + .map_err(|e| Error::CorruptedData(e.to_string())) + ); + } + + Ok(delta).wrap_with_cost(cost) + } + #[cfg(feature = "full")] /// Adds a "Put" op to batch operations for a subtree and key pub fn insert_subtree_into_batch_operations>( @@ -510,15 +654,15 @@ mod tests { merk.commit(grove_version); - let (inserted, previous) = Element::new_item(b"value".to_vec()) + let element = Element::new_item(b"value".to_vec()); + let delta = element .insert_if_changed_value(&mut merk, b"another-key", None, grove_version) .unwrap() .expect("expected successful insertion 2"); merk.commit(grove_version); - assert!(!inserted); - assert_eq!(previous, None); + assert!(!delta.has_changed()); assert_eq!( Element::get(&merk, b"another-key", true, grove_version) .unwrap() @@ -532,7 +676,9 @@ mod tests { let grove_version = GroveVersion::latest(); let storage = TempStorage::new(); let batch = StorageBatch::new(); - let mut merk = empty_path_merk(&*storage, &batch, grove_version); + let tx = storage.start_transaction(); + + let mut merk = empty_path_merk(&*storage, &batch, &tx, grove_version); Element::empty_tree() .insert(&mut merk, b"mykey", None, grove_version) @@ -544,25 +690,26 @@ mod tests { .expect("expected successful insertion 2"); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .unwrap(); let batch = StorageBatch::new(); - let mut merk = empty_path_merk(&*storage, &batch, grove_version); - let (inserted, previous) = Element::new_item(b"value2".to_vec()) + let mut merk = empty_path_merk(&*storage, &batch, &tx, grove_version); + let element = Element::new_item(b"value2".to_vec()); + let delta = element .insert_if_changed_value(&mut merk, b"another-key", None, grove_version) .unwrap() .expect("expected successful insertion 2"); - assert!(inserted); - assert_eq!(previous, Some(Element::new_item(b"value".to_vec())),); + assert!(delta.has_changed()); + assert_eq!(delta.old, Some(Element::new_item(b"value".to_vec())),); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .unwrap(); - let merk = empty_path_merk_read_only(&*storage, grove_version); + let merk = empty_path_merk_read_only(&*storage, &tx, grove_version); assert_eq!( Element::get(&merk, b"another-key", true, grove_version) @@ -580,13 +727,14 @@ mod tests { .insert(&mut merk, b"mykey", None, grove_version) .unwrap() .expect("expected successful insertion"); - let (inserted, previous) = Element::new_item(b"value2".to_vec()) + let element = Element::new_item(b"value2".to_vec()); + let delta = element .insert_if_changed_value(&mut merk, b"another-key", None, grove_version) .unwrap() .expect("expected successful insertion 2"); - assert!(inserted); - assert_eq!(previous, None); + assert!(delta.has_changed()); + assert_eq!(delta.old, None); assert_eq!( Element::get(&merk, b"another-key", true, grove_version) diff --git a/grovedb/src/element/mod.rs b/grovedb/src/element/mod.rs index 9986c6244..7594fbb2c 100644 --- a/grovedb/src/element/mod.rs +++ b/grovedb/src/element/mod.rs @@ -60,7 +60,6 @@ pub const SUM_ITEM_COST_SIZE: u32 = SUM_VALUE_EXTRA_COST + 2; // 11 /// The cost of a sum tree pub const SUM_TREE_COST_SIZE: u32 = SUM_LAYER_COST_SIZE; // 12 -#[cfg(any(feature = "full", feature = "verify"))] /// int 64 sum value pub type SumValue = i64; diff --git a/grovedb/src/element/query.rs b/grovedb/src/element/query.rs index 7226db553..594961509 100644 --- a/grovedb/src/element/query.rs +++ b/grovedb/src/element/query.rs @@ -19,15 +19,15 @@ use grovedb_path::SubtreePath; #[cfg(feature = "full")] use grovedb_storage::{rocksdb_storage::RocksDbStorage, RawIterator, StorageContext}; #[cfg(feature = "full")] -use grovedb_version::{ - check_grovedb_v0, check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0, check_grovedb_v0_with_cost, version::GroveVersion}; #[cfg(feature = "full")] use crate::operations::proof::util::hex_to_ascii; #[cfg(any(feature = "full", feature = "verify"))] use crate::Element; #[cfg(feature = "full")] +use crate::Transaction; +#[cfg(feature = "full")] use crate::{ element::helpers::raw_decode, query_result_type::{ @@ -37,7 +37,6 @@ use crate::{ QueryPathKeyElementTrioResultType, }, }, - util::{merk_optional_tx, merk_optional_tx_internal_error, storage_context_optional_tx}, Error, PathQuery, TransactionArg, }; #[cfg(feature = "full")] @@ -310,6 +309,8 @@ impl Element { add_element_function: fn(PathQueryPushArgs, &GroveVersion) -> CostResult<(), Error>, grove_version: &GroveVersion, ) -> CostResult<(QueryResultElements, u16), Error> { + use crate::util::TxRef; + check_grovedb_v0_with_cost!( "get_query_apply_function", grove_version @@ -326,6 +327,8 @@ impl Element { let original_offset = sized_query.offset; let mut offset = original_offset; + let tx = TxRef::new(storage, transaction); + if sized_query.query.left_to_right { for item in sized_query.query.iter() { cost_return_on_error!( @@ -336,7 +339,7 @@ impl Element { &mut results, path, sized_query, - transaction, + tx.as_ref(), &mut limit, &mut offset, query_options, @@ -359,7 +362,7 @@ impl Element { &mut results, path, sized_query, - transaction, + tx.as_ref(), &mut limit, &mut offset, query_options, @@ -449,6 +452,8 @@ impl Element { args: PathQueryPushArgs, grove_version: &GroveVersion, ) -> CostResult<(), Error> { + use crate::util::{self, TxRef}; + check_grovedb_v0_with_cost!( "path_query_push", grove_version.grovedb_versions.element.path_query_push @@ -479,10 +484,13 @@ impl Element { decrease_limit_on_range_with_no_sub_elements, .. } = query_options; + + let tx = TxRef::new(storage, transaction); + if element.is_any_tree() { let mut path_vec = path.to_vec(); let key = cost_return_on_error_no_add!( - &cost, + cost, key.ok_or(Error::MissingParameter( "the key must be provided when using a subquery path", )) @@ -531,88 +539,62 @@ impl Element { let subtree_path: SubtreePath<_> = path_vec.as_slice().into(); + let subtree = cost_return_on_error!( + &mut cost, + util::open_transactional_merk_at_path( + storage, + subtree_path, + tx.as_ref(), + None, + grove_version + ) + ); + match result_type { QueryElementResultType => { - merk_optional_tx!( - &mut cost, - storage, - subtree_path, - None, - transaction, - subtree, - grove_version, - { - results.push(QueryResultElement::ElementResultItem( - cost_return_on_error!( - &mut cost, - Element::get_with_absolute_refs( - &subtree, - path_vec.as_slice(), - subquery_path_last_key.as_slice(), - allow_cache, - grove_version, - ) - ), - )); - } - ); + results.push(QueryResultElement::ElementResultItem( + cost_return_on_error!( + &mut cost, + Element::get_with_absolute_refs( + &subtree, + path_vec.as_slice(), + subquery_path_last_key.as_slice(), + allow_cache, + grove_version, + ) + ), + )); } QueryKeyElementPairResultType => { - merk_optional_tx!( - &mut cost, - storage, - subtree_path, - None, - transaction, - subtree, - grove_version, - { - results.push(QueryResultElement::KeyElementPairResultItem( - ( - subquery_path_last_key.to_vec(), - cost_return_on_error!( - &mut cost, - Element::get_with_absolute_refs( - &subtree, - path_vec.as_slice(), - subquery_path_last_key.as_slice(), - allow_cache, - grove_version, - ) - ), - ), - )); - } - ); + results.push(QueryResultElement::KeyElementPairResultItem(( + subquery_path_last_key.to_vec(), + cost_return_on_error!( + &mut cost, + Element::get_with_absolute_refs( + &subtree, + path_vec.as_slice(), + subquery_path_last_key.as_slice(), + allow_cache, + grove_version, + ) + ), + ))); } QueryPathKeyElementTrioResultType => { - merk_optional_tx!( - &mut cost, - storage, - subtree_path, - None, - transaction, - subtree, - grove_version, - { - results.push( - QueryResultElement::PathKeyElementTrioResultItem(( - path_vec.iter().map(|p| p.to_vec()).collect(), - subquery_path_last_key.to_vec(), - cost_return_on_error!( - &mut cost, - Element::get_with_absolute_refs( - &subtree, - path_vec.as_slice(), - subquery_path_last_key.as_slice(), - allow_cache, - grove_version, - ) - ), - )), - ); - } - ); + results.push(QueryResultElement::PathKeyElementTrioResultItem(( + path_vec.iter().map(|p| p.to_vec()).collect(), + subquery_path_last_key.to_vec(), + cost_return_on_error!( + &mut cost, + Element::get_with_absolute_refs( + &subtree, + path_vec.as_slice(), + subquery_path_last_key.as_slice(), + allow_cache, + grove_version, + ) + ), + ))); } } } else { @@ -630,7 +612,7 @@ impl Element { } } else if allow_get_raw { cost_return_on_error_no_add!( - &cost, + cost, Element::basic_push( PathQueryPushArgs { storage, @@ -660,7 +642,7 @@ impl Element { } } else { cost_return_on_error_no_add!( - &cost, + cost, Element::basic_push( PathQueryPushArgs { storage, @@ -733,7 +715,7 @@ impl Element { results: &mut Vec, path: &[&[u8]], sized_query: &SizedQuery, - transaction: TransactionArg, + transaction: &Transaction, limit: &mut Option, offset: &mut Option, query_options: QueryOptions, @@ -741,6 +723,10 @@ impl Element { add_element_function: fn(PathQueryPushArgs, &GroveVersion) -> CostResult<(), Error>, grove_version: &GroveVersion, ) -> CostResult<(), Error> { + use grovedb_storage::Storage; + + use crate::util::{self}; + check_grovedb_v0_with_cost!( "query_item", grove_version.grovedb_versions.element.query_item @@ -753,19 +739,16 @@ impl Element { if !item.is_range() { // this is a query on a key if let QueryItem::Key(key) = item { - let element_res = merk_optional_tx_internal_error!( - &mut cost, + let element_res = util::open_transactional_merk_at_path( storage, subtree_path, - None, transaction, - subtree, + None, grove_version, - { - Element::get(&subtree, key, query_options.allow_cache, grove_version) - .unwrap_add_cost(&mut cost) - } - ); + ) + .flat_map_ok(|s| Element::get(&s, key, query_options.allow_cache, grove_version)) + .unwrap_add_cost(&mut cost); + match element_res { Ok(element) => { let (subquery_path, subquery) = @@ -773,7 +756,7 @@ impl Element { match add_element_function( PathQueryPushArgs { storage, - transaction, + transaction: Some(transaction), key: Some(key.as_slice()), element, path, @@ -794,7 +777,7 @@ impl Element { Err(e) => { if !query_options.error_if_intermediate_path_tree_not_present { match e { - Error::PathParentLayerNotFound(_) => Ok(()), + Error::InvalidParentLayerPath(_) => Ok(()), _ => Err(e), } } else { @@ -807,7 +790,7 @@ impl Element { Err(e) => { if !query_options.error_if_intermediate_path_tree_not_present { match e { - Error::PathParentLayerNotFound(_) => Ok(()), + Error::InvalidParentLayerPath(_) => Ok(()), _ => Err(e), } } else { @@ -822,74 +805,74 @@ impl Element { } } else { // this is a query on a range - storage_context_optional_tx!(storage, subtree_path, None, transaction, ctx, { - let ctx = ctx.unwrap_add_cost(&mut cost); - let mut iter = ctx.raw_iter(); + let ctx = storage + .get_transactional_storage_context(subtree_path, None, transaction) + .unwrap_add_cost(&mut cost); - item.seek_for_iter(&mut iter, sized_query.query.left_to_right) - .unwrap_add_cost(&mut cost); + let mut iter = ctx.raw_iter(); - while item - .iter_is_valid_for_type(&iter, *limit, sized_query.query.left_to_right) + item.seek_for_iter(&mut iter, sized_query.query.left_to_right) + .unwrap_add_cost(&mut cost); + + while item + .iter_is_valid_for_type(&iter, *limit, sized_query.query.left_to_right) + .unwrap_add_cost(&mut cost) + { + let element = cost_return_on_error_no_add!( + cost, + raw_decode( + iter.value() + .unwrap_add_cost(&mut cost) + .expect("if key exists then value should too"), + grove_version + ) + ); + let key = iter + .key() .unwrap_add_cost(&mut cost) - { - let element = cost_return_on_error_no_add!( - &cost, - raw_decode( - iter.value() - .unwrap_add_cost(&mut cost) - .expect("if key exists then value should too"), - grove_version - ) - ); - let key = iter - .key() - .unwrap_add_cost(&mut cost) - .expect("key should exist"); - let (subquery_path, subquery) = - Self::subquery_paths_and_value_for_sized_query(sized_query, key); - let result_with_cost = add_element_function( - PathQueryPushArgs { - storage, - transaction, - key: Some(key), - element, - path, - subquery_path, - subquery, - left_to_right: sized_query.query.left_to_right, - query_options, - result_type, - results, - limit, - offset, - }, - grove_version, - ); - let result = result_with_cost.unwrap_add_cost(&mut cost); - match result { - Ok(x) => x, - Err(e) => { - if !query_options.error_if_intermediate_path_tree_not_present { - match e { - Error::PathKeyNotFound(_) - | Error::PathParentLayerNotFound(_) => (), - _ => return Err(e).wrap_with_cost(cost), - } - } else { - return Err(e).wrap_with_cost(cost); + .expect("key should exist"); + let (subquery_path, subquery) = + Self::subquery_paths_and_value_for_sized_query(sized_query, key); + let result_with_cost = add_element_function( + PathQueryPushArgs { + storage, + transaction: Some(transaction), + key: Some(key), + element, + path, + subquery_path, + subquery, + left_to_right: sized_query.query.left_to_right, + query_options, + result_type, + results, + limit, + offset, + }, + grove_version, + ); + let result = result_with_cost.unwrap_add_cost(&mut cost); + match result { + Ok(x) => x, + Err(e) => { + if !query_options.error_if_intermediate_path_tree_not_present { + match e { + Error::PathKeyNotFound(_) | Error::InvalidParentLayerPath(_) => (), + _ => return Err(e).wrap_with_cost(cost), } + } else { + return Err(e).wrap_with_cost(cost); } } - if sized_query.query.left_to_right { - iter.next().unwrap_add_cost(&mut cost); - } else { - iter.prev().unwrap_add_cost(&mut cost); - } - cost.seek_count += 1; } - Ok(()) - }) + if sized_query.query.left_to_right { + iter.next().unwrap_add_cost(&mut cost); + } else { + iter.prev().unwrap_add_cost(&mut cost); + } + cost.seek_count += 1; + } + Ok(()) } .wrap_with_cost(cost) } @@ -1034,13 +1017,13 @@ mod tests { &query, QueryOptions::default(), None, - grove_version + grove_version, ) .unwrap() .expect("expected successful get_query"), vec![ Element::new_item(b"ayya".to_vec()), - Element::new_item(b"ayyc".to_vec()) + Element::new_item(b"ayyc".to_vec()), ] ); @@ -1055,14 +1038,14 @@ mod tests { &query, QueryOptions::default(), None, - grove_version + grove_version, ) .unwrap() .expect("expected successful get_query"), vec![ Element::new_item(b"ayya".to_vec()), Element::new_item(b"ayyb".to_vec()), - Element::new_item(b"ayyc".to_vec()) + Element::new_item(b"ayyc".to_vec()), ] ); @@ -1077,14 +1060,14 @@ mod tests { &query, QueryOptions::default(), None, - grove_version + grove_version, ) .unwrap() .expect("expected successful get_query"), vec![ Element::new_item(b"ayyb".to_vec()), Element::new_item(b"ayyc".to_vec()), - Element::new_item(b"ayyd".to_vec()) + Element::new_item(b"ayyd".to_vec()), ] ); @@ -1100,14 +1083,14 @@ mod tests { &query, QueryOptions::default(), None, - grove_version + grove_version, ) .unwrap() .expect("expected successful get_query"), vec![ Element::new_item(b"ayya".to_vec()), Element::new_item(b"ayyb".to_vec()), - Element::new_item(b"ayyc".to_vec()) + Element::new_item(b"ayyc".to_vec()), ] ); } @@ -1170,7 +1153,7 @@ mod tests { QueryOptions::default(), QueryPathKeyElementTrioResultType, None, - grove_version + grove_version, ) .unwrap() .expect("expected successful get_query") @@ -1185,7 +1168,7 @@ mod tests { vec![TEST_LEAF.to_vec()], b"c".to_vec(), Element::new_item(b"ayyc".to_vec()) - ) + ), ] ); } @@ -1197,9 +1180,12 @@ mod tests { let batch = StorageBatch::new(); let storage = &db.db; + let tx = db.start_transaction(); + let mut merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -1307,11 +1293,13 @@ mod tests { let db = make_test_grovedb(grove_version); let batch = StorageBatch::new(); - + let tx = db.start_transaction(); let storage = &db.db; + let mut merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -1532,7 +1520,7 @@ mod tests { .expect("expected successful get_query"); assert_eq!( elements.to_key_elements(), - vec![(b"c".to_vec(), Element::new_item(b"ayyc".to_vec())),] + vec![(b"c".to_vec(), Element::new_item(b"ayyc".to_vec()))] ); assert_eq!(skipped, 0); @@ -1556,7 +1544,7 @@ mod tests { elements.to_key_elements(), vec![ (b"a".to_vec(), Element::new_item(b"ayya".to_vec())), - (b"b".to_vec(), Element::new_item(b"ayyb".to_vec())) + (b"b".to_vec(), Element::new_item(b"ayyb".to_vec())), ] ); assert_eq!(skipped, 0); @@ -1577,7 +1565,7 @@ mod tests { elements.to_key_elements(), vec![ (b"b".to_vec(), Element::new_item(b"ayyb".to_vec())), - (b"c".to_vec(), Element::new_item(b"ayyc".to_vec())) + (b"c".to_vec(), Element::new_item(b"ayyc".to_vec())), ] ); assert_eq!(skipped, 1); @@ -1603,7 +1591,7 @@ mod tests { elements.to_key_elements(), vec![ (b"b".to_vec(), Element::new_item(b"ayyb".to_vec())), - (b"a".to_vec(), Element::new_item(b"ayya".to_vec())) + (b"a".to_vec(), Element::new_item(b"ayya".to_vec())), ] ); assert_eq!(skipped, 1); @@ -1711,7 +1699,7 @@ impl ElementsIterator { .unwrap_add_cost(&mut cost) .zip(self.raw_iter.value().unwrap_add_cost(&mut cost)) { - let element = cost_return_on_error_no_add!(&cost, raw_decode(value, grove_version)); + let element = cost_return_on_error_no_add!(cost, raw_decode(value, grove_version)); let key_vec = key.to_vec(); self.raw_iter.next().unwrap_add_cost(&mut cost); Some((key_vec, element)) diff --git a/grovedb/src/element/serialize.rs b/grovedb/src/element/serialize.rs index 395fea8dd..086312399 100644 --- a/grovedb/src/element/serialize.rs +++ b/grovedb/src/element/serialize.rs @@ -2,7 +2,7 @@ //! Implements serialization functions in Element use bincode::config; -use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; +use grovedb_version::{check_grovedb_v0, version::GroveVersion}; #[cfg(any(feature = "full", feature = "verify"))] use crate::{Element, Error}; diff --git a/grovedb/src/error.rs b/grovedb/src/error.rs index 923439352..6775b74e6 100644 --- a/grovedb/src/error.rs +++ b/grovedb/src/error.rs @@ -42,10 +42,6 @@ pub enum Error { /// isn't there #[error("path not found: {0}")] PathNotFound(String), - /// The path not found could represent a valid query, just where the parent - /// path merk isn't there - #[error("path parent layer not found: {0}")] - PathParentLayerNotFound(String), /// The path's item by key referenced was not found #[error("corrupted referenced path key not found: {0}")] @@ -57,6 +53,10 @@ pub enum Error { #[error("corrupted referenced path key not found: {0}")] CorruptedReferencePathParentLayerNotFound(String), + /// Bidirectional references rule was violated + #[error("bidirectional reference rule violation: {0}")] + BidirectionalReferenceRule(String), + /// The invalid parent layer path represents a logical error from the client /// library #[error("invalid parent layer path: {0}")] diff --git a/grovedb/src/estimated_costs/average_case_costs.rs b/grovedb/src/estimated_costs/average_case_costs.rs index 74cfe8073..1eeea0b70 100644 --- a/grovedb/src/estimated_costs/average_case_costs.rs +++ b/grovedb/src/estimated_costs/average_case_costs.rs @@ -16,9 +16,7 @@ use grovedb_merk::{ HASH_LENGTH, }; use grovedb_storage::{worst_case_costs::WorstKeyLength, Storage}; -use grovedb_version::{ - check_grovedb_v0, check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0, check_grovedb_v0_with_cost, version::GroveVersion}; use integer_encoding::VarInt; use crate::{ @@ -85,7 +83,7 @@ impl GroveDb { let mut cost = OperationCost::default(); let key_len = key.max_length() as u32; let flags_size = cost_return_on_error_no_add!( - &cost, + cost, estimated_layer_information .estimated_layer_sizes .layered_flags_size() @@ -173,7 +171,7 @@ impl GroveDb { let mut cost = OperationCost::default(); let key_len = key.max_length() as u32; let flags_size = cost_return_on_error_no_add!( - &cost, + cost, estimated_layer_information .estimated_layer_sizes .layered_flags_size() @@ -235,7 +233,7 @@ impl GroveDb { _ => add_cost_case_merk_insert( &mut cost, key_len, - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) as u32, + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32, in_tree_using_sums, ), }; @@ -296,7 +294,7 @@ impl GroveDb { let sum_item_cost_size = if value.is_sum_item() { SUM_ITEM_COST_SIZE } else { - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) as u32 + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32 }; let value_len = sum_item_cost_size + flags_len; add_cost_case_merk_replace_same_size( @@ -309,7 +307,7 @@ impl GroveDb { _ => add_cost_case_merk_replace_same_size( &mut cost, key_len, - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) as u32, + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32, in_tree_using_sums, ), }; @@ -351,8 +349,7 @@ impl GroveDb { }); // Items need to be always the same serialized size for this to work let item_cost_size = - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) - as u32; + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32; let value_len = item_cost_size + flags_len; add_cost_case_merk_patch( &mut cost, @@ -394,7 +391,7 @@ impl GroveDb { let mut cost = OperationCost::default(); let key_len = key.max_length() as u32; let value_size = cost_return_on_error_no_add!( - &cost, + cost, estimated_layer_information .estimated_layer_sizes .value_with_feature_and_flags_size() @@ -601,10 +598,11 @@ mod test { let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(EMPTY_PATH, Some(&batch)) + .get_transactional_storage_context(EMPTY_PATH, Some(&batch), &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -619,13 +617,15 @@ mod test { // this consumes the batch so storage contexts and merks will be dropped storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .unwrap(); // Reopen merk: this time, only root node is loaded to memory let merk = Merk::open_base( - storage.get_storage_context(EMPTY_PATH, None).unwrap(), + storage + .get_transactional_storage_context(EMPTY_PATH, None, &tx) + .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, grove_version, diff --git a/grovedb/src/estimated_costs/worst_case_costs.rs b/grovedb/src/estimated_costs/worst_case_costs.rs index 4c409b999..304deaeb8 100644 --- a/grovedb/src/estimated_costs/worst_case_costs.rs +++ b/grovedb/src/estimated_costs/worst_case_costs.rs @@ -18,9 +18,7 @@ use grovedb_merk::{ HASH_LENGTH, }; use grovedb_storage::{worst_case_costs::WorstKeyLength, Storage}; -use grovedb_version::{ - check_grovedb_v0, check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0, check_grovedb_v0_with_cost, version::GroveVersion}; use integer_encoding::VarInt; use crate::{ @@ -221,7 +219,7 @@ impl GroveDb { _ => add_cost_case_merk_insert( &mut cost, key_len, - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) as u32, + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32, in_parent_tree_using_sums, ), }; @@ -289,7 +287,7 @@ impl GroveDb { _ => add_cost_case_merk_replace( &mut cost, key_len, - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) as u32, + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32, in_parent_tree_using_sums, ), }; @@ -331,8 +329,7 @@ impl GroveDb { }); // Items need to be always the same serialized size for this to work let sum_item_cost_size = - cost_return_on_error_no_add!(&cost, value.serialized_size(grove_version)) - as u32; + cost_return_on_error_no_add!(cost, value.serialized_size(grove_version)) as u32; let value_len = sum_item_cost_size + flags_len; add_cost_case_merk_patch( &mut cost, @@ -536,7 +533,9 @@ mod test { // Open a merk and insert 10 elements. let storage = TempStorage::new(); let batch = StorageBatch::new(); - let mut merk = empty_path_merk(&*storage, &batch, grove_version); + let tx = storage.start_transaction(); + + let mut merk = empty_path_merk(&*storage, &batch, &tx, grove_version); let merk_batch = make_batch_seq(1..10); merk.apply::<_, Vec<_>>(merk_batch.as_slice(), &[], None, grove_version) @@ -545,12 +544,12 @@ mod test { // this consumes the batch so storage contexts and merks will be dropped storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .unwrap(); // Reopen merk: this time, only root node is loaded to memory - let merk = empty_path_merk_read_only(&*storage, grove_version); + let merk = empty_path_merk_read_only(&*storage, &tx, grove_version); // To simulate worst case, we need to pick a node that: // 1. Is not in memory diff --git a/grovedb/src/lib.rs b/grovedb/src/lib.rs index 57f68d33e..b7741acf1 100644 --- a/grovedb/src/lib.rs +++ b/grovedb/src/lib.rs @@ -135,6 +135,8 @@ pub mod element; pub mod error; #[cfg(feature = "estimated_costs")] mod estimated_costs; +#[cfg(feature = "full")] +mod merk_cache; #[cfg(any(feature = "full", feature = "verify"))] pub mod operations; #[cfg(any(feature = "full", feature = "verify"))] @@ -193,10 +195,7 @@ use grovedb_storage::rocksdb_storage::PrefixedRocksDbImmediateStorageContext; #[cfg(feature = "full")] use grovedb_storage::rocksdb_storage::RocksDbStorage; #[cfg(feature = "full")] -use grovedb_storage::{ - rocksdb_storage::{PrefixedRocksDbStorageContext, PrefixedRocksDbTransactionContext}, - StorageBatch, -}; +use grovedb_storage::{rocksdb_storage::PrefixedRocksDbTransactionContext, StorageBatch}; #[cfg(feature = "full")] use grovedb_storage::{Storage, StorageContext}; #[cfg(feature = "full")] @@ -209,6 +208,7 @@ pub use query::{PathQuery, SizedQuery}; use reference_path::path_from_reference_path_type; #[cfg(feature = "grovedbg")] use tokio::net::ToSocketAddrs; +use util::TxRef; #[cfg(feature = "full")] use crate::element::helpers::raw_decode; @@ -217,8 +217,6 @@ pub use crate::error::Error; #[cfg(feature = "full")] use crate::operations::proof::util::hex_to_ascii; #[cfg(feature = "full")] -use crate::util::{root_merk_optional_tx, storage_context_optional_tx}; -#[cfg(feature = "full")] use crate::Error::MerkError; #[cfg(feature = "full")] @@ -275,59 +273,7 @@ impl GroveDb { where B: AsRef<[u8]> + 'b, { - let mut cost = OperationCost::default(); - - let storage = self - .db - .get_transactional_storage_context(path.clone(), batch, tx) - .unwrap_add_cost(&mut cost); - if let Some((parent_path, parent_key)) = path.derive_parent() { - let parent_storage = self - .db - .get_transactional_storage_context(parent_path.clone(), batch, tx) - .unwrap_add_cost(&mut cost); - let element = cost_return_on_error!( - &mut cost, - Element::get_from_storage(&parent_storage, parent_key, grove_version).map_err( - |e| { - Error::InvalidParentLayerPath(format!( - "could not get key {} for parent {:?} of subtree: {}", - hex::encode(parent_key), - DebugByteVectors(parent_path.to_vec()), - e - )) - } - ) - ); - let is_sum_tree = element.is_sum_tree(); - if let Element::Tree(root_key, _) | Element::SumTree(root_key, ..) = element { - Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version, - ) - .map_err(|_| { - Error::CorruptedData("cannot open a subtree with given root key".to_owned()) - }) - .add_cost(cost) - } else { - Err(Error::CorruptedPath( - "cannot open a subtree as parent exists but is not a tree".to_string(), - )) - .wrap_with_cost(cost) - } - } else { - Merk::open_base( - storage, - false, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version, - ) - .map_err(|_| Error::CorruptedData("cannot open a the root subtree".to_owned())) - .add_cost(cost) - } + util::open_transactional_merk_at_path(&self.db, path, tx, batch, grove_version) } /// Opens a Merk at given path for with direct write access. Intended for @@ -392,75 +338,31 @@ impl GroveDb { } } - /// Opens the non-transactional Merk at the given path. Returns CostResult. - fn open_non_transactional_merk_at_path<'db, 'b, B>( + /// Creates a checkpoint + pub fn create_checkpoint>(&self, path: P) -> Result<(), Error> { + self.db.create_checkpoint(path).map_err(|e| e.into()) + } + + fn open_root_merk<'tx, 'db>( &'db self, - path: SubtreePath<'b, B>, - batch: Option<&'db StorageBatch>, + tx: &'tx Transaction<'db>, grove_version: &GroveVersion, - ) -> CostResult, Error> - where - B: AsRef<[u8]> + 'b, - { - let mut cost = OperationCost::default(); - - let storage = self - .db - .get_storage_context(path.clone(), batch) - .unwrap_add_cost(&mut cost); - - if let Some((parent_path, parent_key)) = path.derive_parent() { - let parent_storage = self - .db - .get_storage_context(parent_path.clone(), batch) - .unwrap_add_cost(&mut cost); - let element = cost_return_on_error!( - &mut cost, - Element::get_from_storage(&parent_storage, parent_key, grove_version).map_err( - |e| { - Error::InvalidParentLayerPath(format!( - "could not get key {} for parent {:?} of subtree: {}", - hex::encode(parent_key), - DebugByteVectors(parent_path.to_vec()), - e - )) - } - ) - ); - let is_sum_tree = element.is_sum_tree(); - if let Element::Tree(root_key, _) | Element::SumTree(root_key, ..) = element { - Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), + ) -> CostResult>, Error> { + self.db + .get_transactional_storage_context(SubtreePath::empty(), None, tx) + .flat_map(|storage_ctx| { + grovedb_merk::Merk::open_base( + storage_ctx, + false, + Some(Element::value_defined_cost_for_serialized_value), grove_version, ) - .map_err(|_| { - Error::CorruptedData("cannot open a subtree with given root key".to_owned()) + .map(|merk_res| { + merk_res.map_err(|_| { + crate::Error::CorruptedData("cannot open a subtree".to_owned()) + }) }) - .add_cost(cost) - } else { - Err(Error::CorruptedPath( - "cannot open a subtree as parent exists but is not a tree".to_string(), - )) - .wrap_with_cost(cost) - } - } else { - Merk::open_base( - storage, - false, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version, - ) - .map_err(|_| Error::CorruptedData("cannot open a the root subtree".to_owned())) - .add_cost(cost) - } - } - - /// Creates a checkpoint - pub fn create_checkpoint>(&self, path: P) -> Result<(), Error> { - self.db.create_checkpoint(path).map_err(|e| e.into()) + }) } /// Returns root key of GroveDb. @@ -469,23 +371,11 @@ impl GroveDb { &self, transaction: TransactionArg, grove_version: &GroveVersion, - ) -> CostResult, Error> { - let mut cost = OperationCost { - ..Default::default() - }; + ) -> CostResult>, Error> { + let tx = TxRef::new(&self.db, transaction); - root_merk_optional_tx!( - &mut cost, - self.db, - None, - transaction, - subtree, - grove_version, - { - let root_key = subtree.root_key().unwrap(); - Ok(root_key).wrap_with_cost(cost) - } - ) + self.open_root_merk(tx.as_ref(), grove_version) + .map_ok(|merk| merk.root_key()) } /// Returns root hash of GroveDb. @@ -495,75 +385,12 @@ impl GroveDb { transaction: TransactionArg, grove_version: &GroveVersion, ) -> CostResult { - let mut cost = OperationCost { - ..Default::default() - }; + let tx = TxRef::new(&self.db, transaction); + let mut cost = Default::default(); - root_merk_optional_tx!( - &mut cost, - self.db, - None, - transaction, - subtree, - grove_version, - { - let root_hash = subtree.root_hash().unwrap_add_cost(&mut cost); - Ok(root_hash).wrap_with_cost(cost) - } - ) - } - - /// Method to propagate updated subtree key changes one level up inside a - /// transaction - fn propagate_changes_with_batch_transaction<'b, B: AsRef<[u8]>>( - &self, - storage_batch: &StorageBatch, - mut merk_cache: HashMap, Merk>, - path: &SubtreePath<'b, B>, - transaction: &Transaction, - grove_version: &GroveVersion, - ) -> CostResult<(), Error> { - let mut cost = OperationCost::default(); - - let mut child_tree = cost_return_on_error_no_add!( - &cost, - merk_cache.remove(path).ok_or(Error::CorruptedCodeExecution( - "Merk Cache should always contain the last path", - )) - ); - - let mut current_path = path.clone(); - - while let Some((parent_path, parent_key)) = current_path.derive_parent() { - let mut parent_tree = cost_return_on_error!( - &mut cost, - self.open_batch_transactional_merk_at_path( - storage_batch, - parent_path.clone(), - transaction, - false, - grove_version, - ) - ); - let (root_hash, root_key, sum) = cost_return_on_error!( - &mut cost, - child_tree.root_hash_key_and_sum().map_err(Error::MerkError) - ); - cost_return_on_error!( - &mut cost, - Self::update_tree_item_preserve_flag( - &mut parent_tree, - parent_key, - root_key, - root_hash, - sum, - grove_version, - ) - ); - child_tree = parent_tree; - current_path = parent_path; - } - Ok(()).wrap_with_cost(cost) + let subtree = + cost_return_on_error!(&mut cost, self.open_root_merk(tx.as_ref(), grove_version)); + subtree.root_hash().map(Ok).add_cost(cost) } /// Method to propagate updated subtree key changes one level up inside a @@ -579,7 +406,7 @@ impl GroveDb { let mut cost = OperationCost::default(); let mut child_tree = cost_return_on_error_no_add!( - &cost, + cost, merk_cache .remove(&path) .ok_or(Error::CorruptedCodeExecution( @@ -620,57 +447,6 @@ impl GroveDb { Ok(()).wrap_with_cost(cost) } - /// Method to propagate updated subtree key changes one level up - fn propagate_changes_without_transaction<'b, B: AsRef<[u8]>>( - &self, - mut merk_cache: HashMap, Merk>, - path: SubtreePath<'b, B>, - batch: &StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult<(), Error> { - let mut cost = OperationCost::default(); - - let mut child_tree = cost_return_on_error_no_add!( - &cost, - merk_cache - .remove(&path) - .ok_or(Error::CorruptedCodeExecution( - "Merk Cache should always contain the last path", - )) - ); - - let mut current_path: SubtreePath = path; - - while let Some((parent_path, parent_key)) = current_path.derive_parent() { - let mut parent_tree: Merk = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path( - parent_path.clone(), - Some(batch), - grove_version - ) - ); - let (root_hash, root_key, sum) = cost_return_on_error!( - &mut cost, - child_tree.root_hash_key_and_sum().map_err(Error::MerkError) - ); - cost_return_on_error!( - &mut cost, - Self::update_tree_item_preserve_flag( - &mut parent_tree, - parent_key, - root_key, - root_hash, - sum, - grove_version, - ) - ); - child_tree = parent_tree; - current_path = parent_path; - } - Ok(()).wrap_with_cost(cost) - } - /// Updates a tree item and preserves flags. Returns CostResult. pub(crate) fn update_tree_item_preserve_flag<'db, K: AsRef<[u8]>, S: StorageContext<'db>>( parent_tree: &mut Merk, @@ -936,182 +712,18 @@ impl GroveDb { allow_cache: bool, grove_version: &GroveVersion, ) -> Result>, (CryptoHash, CryptoHash, CryptoHash)>, Error> { - if let Some(transaction) = transaction { - let root_merk = self - .open_transactional_merk_at_path( - SubtreePath::empty(), - transaction, - None, - grove_version, - ) - .unwrap()?; - self.verify_merk_and_submerks_in_transaction( - root_merk, - &SubtreePath::empty(), - None, - transaction, - verify_references, - allow_cache, - grove_version, - ) - } else { - let root_merk = self - .open_non_transactional_merk_at_path(SubtreePath::empty(), None, grove_version) - .unwrap()?; - self.verify_merk_and_submerks( - root_merk, - &SubtreePath::empty(), - None, - verify_references, - allow_cache, - grove_version, - ) - } - } - - /// Verifies that the root hash of the given merk and all submerks match - /// those of the merk and submerks at the given path. Returns any issues. - fn verify_merk_and_submerks<'db, B: AsRef<[u8]>, S: StorageContext<'db>>( - &'db self, - merk: Merk, - path: &SubtreePath, - batch: Option<&'db StorageBatch>, - verify_references: bool, - allow_cache: bool, - grove_version: &GroveVersion, - ) -> Result>, (CryptoHash, CryptoHash, CryptoHash)>, Error> { - let mut all_query = Query::new(); - all_query.insert_all(); - - let mut issues = HashMap::new(); - let mut element_iterator = KVIterator::new(merk.storage.raw_iter(), &all_query).unwrap(); - - while let Some((key, element_value)) = element_iterator.next_kv().unwrap() { - let element = raw_decode(&element_value, grove_version)?; - match element { - Element::SumTree(..) | Element::Tree(..) => { - let (kv_value, element_value_hash) = merk - .get_value_and_value_hash( - &key, - allow_cache, - None::<&fn(&[u8], &GroveVersion) -> Option>, - grove_version, - ) - .unwrap() - .map_err(MerkError)? - .ok_or(Error::CorruptedData(format!( - "expected merk to contain value at key {} for {}", - hex_to_ascii(&key), - element.type_str() - )))?; - let new_path = path.derive_owned_with_child(key); - let new_path_ref = SubtreePath::from(&new_path); - - let inner_merk = self - .open_non_transactional_merk_at_path( - new_path_ref.clone(), - batch, - grove_version, - ) - .unwrap()?; - let root_hash = inner_merk.root_hash().unwrap(); - - let actual_value_hash = value_hash(&kv_value).unwrap(); - let combined_value_hash = combine_hash(&actual_value_hash, &root_hash).unwrap(); - - if combined_value_hash != element_value_hash { - issues.insert( - new_path.to_vec(), - (root_hash, combined_value_hash, element_value_hash), - ); - } - issues.extend(self.verify_merk_and_submerks( - inner_merk, - &new_path_ref, - batch, - verify_references, - true, - grove_version, - )?); - } - Element::Item(..) | Element::SumItem(..) => { - let (kv_value, element_value_hash) = merk - .get_value_and_value_hash( - &key, - allow_cache, - None::<&fn(&[u8], &GroveVersion) -> Option>, - grove_version, - ) - .unwrap() - .map_err(MerkError)? - .ok_or(Error::CorruptedData(format!( - "expected merk to contain value at key {} for {}", - hex_to_ascii(&key), - element.type_str() - )))?; - let actual_value_hash = value_hash(&kv_value).unwrap(); - if actual_value_hash != element_value_hash { - issues.insert( - path.derive_owned_with_child(key).to_vec(), - (actual_value_hash, element_value_hash, actual_value_hash), - ); - } - } - Element::Reference(ref reference_path, ..) => { - // Skip this whole check if we don't `verify_references` - if !verify_references { - continue; - } - - // Merk we're checking: - let (kv_value, element_value_hash) = merk - .get_value_and_value_hash( - &key, - allow_cache, - None::<&fn(&[u8], &GroveVersion) -> Option>, - grove_version, - ) - .unwrap() - .map_err(MerkError)? - .ok_or(Error::CorruptedData(format!( - "expected merk to contain value at key {} for reference", - hex_to_ascii(&key) - )))?; + let tx = TxRef::new(&self.db, transaction); + let root_merk = self.open_root_merk(tx.as_ref(), grove_version).unwrap()?; - let referenced_value_hash = { - let full_path = path_from_reference_path_type( - reference_path.clone(), - &path.to_vec(), - Some(&key), - )?; - let item = self - .follow_reference( - (full_path.as_slice()).into(), - allow_cache, - None, - grove_version, - ) - .unwrap()?; - item.value_hash(grove_version).unwrap()? - }; - - // Take the current item (reference) hash and combine it with referenced value's - // hash - - let self_actual_value_hash = value_hash(&kv_value).unwrap(); - let combined_value_hash = - combine_hash(&self_actual_value_hash, &referenced_value_hash).unwrap(); - - if combined_value_hash != element_value_hash { - issues.insert( - path.derive_owned_with_child(key).to_vec(), - (combined_value_hash, element_value_hash, combined_value_hash), - ); - } - } - } - } - Ok(issues) + self.verify_merk_and_submerks_in_transaction( + root_merk, + &SubtreePath::empty(), + None, + tx.as_ref(), + verify_references, + allow_cache, + grove_version, + ) } fn verify_merk_and_submerks_in_transaction<'db, B: AsRef<[u8]>, S: StorageContext<'db>>( @@ -1234,7 +846,7 @@ impl GroveDb { .follow_reference( (full_path.as_slice()).into(), allow_cache, - Some(transaction), + transaction, grove_version, ) .unwrap()?; diff --git a/grovedb/src/merk_cache.rs b/grovedb/src/merk_cache.rs new file mode 100644 index 000000000..993a95912 --- /dev/null +++ b/grovedb/src/merk_cache.rs @@ -0,0 +1,266 @@ +//! Module dedicated to keep necessary Merks in memory. + +use std::{ + cell::{Cell, UnsafeCell}, + collections::{btree_map::Entry, BTreeMap}, +}; + +use grovedb_costs::{cost_return_on_error, CostResult, CostsExt}; +use grovedb_merk::Merk; +use grovedb_path::SubtreePathBuilder; +use grovedb_storage::{rocksdb_storage::PrefixedRocksDbTransactionContext, StorageBatch}; +use grovedb_version::version::GroveVersion; + +use crate::{Error, GroveDb, Transaction}; + +type TxMerk<'db> = Merk>; + +/// Structure to keep subtrees open in memory for repeated access. +pub(crate) struct MerkCache<'db, 'b, B: AsRef<[u8]>> { + db: &'db GroveDb, + pub(crate) version: &'db GroveVersion, + batch: Box, + tx: &'db Transaction<'db>, + merks: UnsafeCell, Box<(Cell, TxMerk<'db>)>>>, +} + +impl<'db, 'b, B: AsRef<[u8]>> MerkCache<'db, 'b, B> { + /// Initialize a new `MerkCache` instance + pub(crate) fn new( + db: &'db GroveDb, + tx: &'db Transaction<'db>, + version: &'db GroveVersion, + ) -> Self { + MerkCache { + db, + tx, + version, + merks: Default::default(), + batch: Default::default(), + } + } + + /// Gets a smart pointer to a cached Merk or opens one if needed. + pub(crate) fn get_merk<'c>( + &'c self, + path: SubtreePathBuilder<'b, B>, + ) -> CostResult, Error> { + let mut cost = Default::default(); + + // SAFETY: there are no other references to `merks` memory at the same time. + // Note while it's possible to have direct references to actual Merk trees, + // outside of the scope of this function, this map (`merks`) has + // indirect connection to them through `Box`, thus there are no overlapping + // references, and that is requirement of `UnsafeCell` we have there. + let boxed_flag_merk = match unsafe { + self.merks + .get() + .as_mut() + .expect("`UnsafeCell` is never null") + } + .entry(path) + { + Entry::Vacant(e) => { + let merk = cost_return_on_error!( + &mut cost, + self.db.open_transactional_merk_at_path( + e.key().into(), + self.tx, + // SAFETY: batch is allocated on the heap and we use only shared + // references, so as long as the `Box` allocation + // outlives those references we're safe, + // and it will outlive because Merks are dropped first. + Some(unsafe { + (&*self.batch as *const StorageBatch) + .as_ref() + .expect("`Box` is never null") + }), + self.version + ) + ); + e.insert(Box::new((false.into(), merk))) + } + Entry::Occupied(e) => e.into_mut(), + }; + + let taken_handle_ref: *const Cell = &boxed_flag_merk.0 as *const _; + let merk_ptr: *mut TxMerk<'db> = &mut boxed_flag_merk.1 as *mut _; + + // SAFETY: `MerkHandle` contains two references to the heap allocated memory, + // and we want to be sure that the referenced data will outlive those + // references plus borrowing rules aren't violated (one `&mut` or many + // `&` with no `&mut` at a time). + // + // To make sure changes to the map won't affect existing borrows we have an + // indirection in a form of `Box`, that allows us to move and update + // `MerkCache` with new subtrees and possible reallocations without breaking + // `MerkHandle`'s references. We use `UnsafeCell` to connect lifetimes and check + // in compile time that `MerkHandle`s won't outlive the cache, even though we + // don't hold any references to it, but `&mut` reference would make this borrow + // exclusive for the whole time of `MerkHandle`, so it shall go intially through + // a shared reference. + // + // Borrowing rules are covered using a borrow flag of each Merk: + // 1. Borrow flag's reference points to a heap allocated memory and will remain + // valid. Since the reference is shared and no need to obtain a `&mut` + // reference this part of the memory is covered. + // 2. For the same reason the Merk's pointer can be converted to a reference, + // because the memory behind the `Box` is valid and `MerkHandle` can't + // outlive it since we use lifetime parameters. + // 3. We can get unique reference out of that pointer safely because of + // borrowing flag. + Ok(unsafe { + MerkHandle { + merk: merk_ptr, + taken_handle: taken_handle_ref + .as_ref() + .expect("`Box` contents are never null"), + } + }) + .wrap_with_cost(cost) + } + + /// Consumes `MerkCache` into accumulated batch of uncommited operations + /// with subtrees' root hash propagation done. + pub(crate) fn into_batch(mut self) -> CostResult, Error> { + let mut cost = Default::default(); + cost_return_on_error!(&mut cost, self.propagate_subtrees()); + + // SAFETY: By this time all subtrees are taken and dropped during + // propagation, so there are no more references to the batch and in can be + // safely released into the world. + Ok(self.batch).wrap_with_cost(cost) + } + + fn propagate_subtrees(&mut self) -> CostResult<(), Error> { + let mut cost = Default::default(); + + // This relies on [SubtreePath]'s ordering implementation to put the deepest + // path's first. + while let Some((path, flag_and_merk)) = self.merks.get_mut().pop_first() { + let merk = flag_and_merk.1; + if let Some((parent_path, parent_key)) = path.derive_parent_owned() { + let mut parent_merk = cost_return_on_error!(&mut cost, self.get_merk(parent_path)); + + let (root_hash, root_key, sum) = cost_return_on_error!( + &mut cost, + merk.root_hash_key_and_sum().map_err(Error::MerkError) + ); + cost_return_on_error!( + &mut cost, + parent_merk.for_merk(|m| GroveDb::update_tree_item_preserve_flag( + m, + parent_key, + root_key, + root_hash, + sum, + self.version, + )) + ); + } + } + + Ok(()).wrap_with_cost(cost) + } +} + +/// Wrapper over `Merk` tree to manage unqiue borrow dynamically. +#[derive(Clone)] +pub(crate) struct MerkHandle<'db, 'c> { + merk: *mut TxMerk<'db>, + taken_handle: &'c Cell, +} + +impl<'db, 'c> MerkHandle<'db, 'c> { + pub(crate) fn for_merk(&mut self, f: impl FnOnce(&mut TxMerk<'db>) -> T) -> T { + if self.taken_handle.get() { + panic!("Attempt to have double &mut borrow on Merk"); + } + + self.taken_handle.set(true); + + // SAFETY: here we want to have `&mut` reference to Merk out of a pointer, there + // is a checklist for that: + // 1. Memory is valid, because `MerkHandle` can't outlive `MerkCache` and heap + // allocated Merks stay at their place for the whole `MerkCache` lifetime. + // 2. No other references exist because of `taken_handle` check above. + let result = f(unsafe { self.merk.as_mut().expect("`Box` contents are never null") }); + + self.taken_handle.set(false); + + result + } +} + +#[cfg(test)] +mod tests { + use grovedb_path::SubtreePath; + use grovedb_storage::StorageBatch; + use grovedb_version::version::GroveVersion; + + use super::MerkCache; + use crate::{ + tests::{make_deep_tree, make_test_grovedb, TEST_LEAF}, + Element, + }; + + #[test] + #[should_panic] + fn cant_borrow_twice() { + let version = GroveVersion::latest(); + let db = make_test_grovedb(&version); + let tx = db.start_transaction(); + + let cache = MerkCache::new(&db, &tx, version); + + let mut merk1 = cache + .get_merk(SubtreePath::empty().derive_owned()) + .unwrap() + .unwrap(); + let mut merk2 = cache + .get_merk(SubtreePath::empty().derive_owned()) + .unwrap() + .unwrap(); + + merk1.for_merk(|_m1| { + merk2.for_merk(|_m2| { + // this shouldn't happen + }) + }); + } + + #[test] + fn subtrees_are_propagated() { + let version = GroveVersion::latest(); + let db = make_deep_tree(&version); + let tx = db.start_transaction(); + + let path = SubtreePath::from(&[TEST_LEAF, b"innertree"]); + let item = Element::new_item(b"hello".to_vec()); + + let no_propagation_ops_count = { + let batch = StorageBatch::new(); + + let mut merk = db + .open_transactional_merk_at_path(path.clone(), &tx, Some(&batch), &version) + .unwrap() + .unwrap(); + + item.insert(&mut merk, b"k1", None, &version) + .unwrap() + .unwrap(); + + batch.len() + }; + + let cache = MerkCache::new(&db, &tx, version); + + let mut merk = cache.get_merk(path.derive_owned()).unwrap().unwrap(); + + merk.for_merk(|m| item.insert(m, b"k1", None, &version).unwrap().unwrap()); + + drop(merk); + + assert!(cache.into_batch().unwrap().unwrap().len() > no_propagation_ops_count); + } +} diff --git a/grovedb/src/operations/auxiliary.rs b/grovedb/src/operations/auxiliary.rs index 516796ed5..22b2d9116 100644 --- a/grovedb/src/operations/auxiliary.rs +++ b/grovedb/src/operations/auxiliary.rs @@ -28,22 +28,16 @@ //! Auxiliary operations -#[cfg(feature = "full")] use grovedb_costs::{ - cost_return_on_error, cost_return_on_error_no_add, - storage_cost::key_value_cost::KeyValueStorageCost, CostResult, CostsExt, OperationCost, + cost_return_on_error, storage_cost::key_value_cost::KeyValueStorageCost, CostResult, CostsExt, + OperationCost, }; use grovedb_path::SubtreePath; -#[cfg(feature = "full")] -use grovedb_storage::StorageContext; -use grovedb_storage::{Storage, StorageBatch}; +use grovedb_storage::{Storage, StorageBatch, StorageContext}; use grovedb_version::version::GroveVersion; -use crate::util::storage_context_optional_tx; -#[cfg(feature = "full")] -use crate::{util::meta_storage_context_optional_tx, Element, Error, GroveDb, TransactionArg}; +use crate::{util::TxRef, Element, Error, GroveDb, TransactionArg}; -#[cfg(feature = "full")] impl GroveDb { /// Put op for aux storage pub fn put_aux>( @@ -55,22 +49,26 @@ impl GroveDb { ) -> CostResult<(), Error> { let mut cost = OperationCost::default(); let batch = StorageBatch::new(); + let tx = TxRef::new(&self.db, transaction); - meta_storage_context_optional_tx!(self.db, Some(&batch), transaction, aux_storage, { - cost_return_on_error_no_add!( - &cost, - aux_storage - .unwrap_add_cost(&mut cost) - .put_aux(key.as_ref(), value, cost_info) - .unwrap_add_cost(&mut cost) - .map_err(|e| e.into()) - ); - }); + let storage = self + .db + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), tx.as_ref()) + .unwrap_add_cost(&mut cost); + + cost_return_on_error!( + &mut cost, + storage + .put_aux(key.as_ref(), value, cost_info) + .map_err(|e| e.into()) + ); self.db - .commit_multi_context_batch(batch, transaction) + .commit_multi_context_batch(batch, Some(tx.as_ref())) .add_cost(cost) .map_err(Into::into) + .map_ok(|_| tx.commit_local()) + .flatten() } /// Delete op for aux storage @@ -82,22 +80,26 @@ impl GroveDb { ) -> CostResult<(), Error> { let mut cost = OperationCost::default(); let batch = StorageBatch::new(); + let tx = TxRef::new(&self.db, transaction); + + let storage = self + .db + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), tx.as_ref()) + .unwrap_add_cost(&mut cost); - meta_storage_context_optional_tx!(self.db, Some(&batch), transaction, aux_storage, { - cost_return_on_error_no_add!( - &cost, - aux_storage - .unwrap_add_cost(&mut cost) - .delete_aux(key.as_ref(), cost_info) - .unwrap_add_cost(&mut cost) - .map_err(|e| e.into()) - ); - }); + cost_return_on_error!( + &mut cost, + storage + .delete_aux(key.as_ref(), cost_info) + .map_err(|e| e.into()) + ); self.db - .commit_multi_context_batch(batch, transaction) + .commit_multi_context_batch(batch, Some(tx.as_ref())) .add_cost(cost) .map_err(Into::into) + .map_ok(|_| tx.commit_local()) + .flatten() } /// Get op for aux storage @@ -107,19 +109,15 @@ impl GroveDb { transaction: TransactionArg, ) -> CostResult>, Error> { let mut cost = OperationCost::default(); + let batch = StorageBatch::new(); + let tx = TxRef::new(&self.db, transaction); - meta_storage_context_optional_tx!(self.db, None, transaction, aux_storage, { - let value = cost_return_on_error_no_add!( - &cost, - aux_storage - .unwrap_add_cost(&mut cost) - .get_aux(key) - .unwrap_add_cost(&mut cost) - .map_err(|e| e.into()) - ); - - Ok(value).wrap_with_cost(cost) - }) + let storage = self + .db + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), tx.as_ref()) + .unwrap_add_cost(&mut cost); + + storage.get_aux(key).map_err(|e| e.into()).add_cost(cost) } // TODO: dumb traversal should not be tolerated @@ -134,6 +132,8 @@ impl GroveDb { ) -> CostResult>>, Error> { let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); + // TODO: remove conversion to vec; // However, it's not easy for a reason: // new keys to enqueue are taken from raw iterator which returns Vec; @@ -151,20 +151,22 @@ impl GroveDb { while let Some(q) = queue.pop() { let subtree_path: SubtreePath> = q.as_slice().into(); // Get the correct subtree with q_ref as path - storage_context_optional_tx!(self.db, subtree_path, None, transaction, storage, { - let storage = storage.unwrap_add_cost(&mut cost); - let mut raw_iter = Element::iterator(storage.raw_iter()).unwrap_add_cost(&mut cost); - while let Some((key, value)) = - cost_return_on_error!(&mut cost, raw_iter.next_element(grove_version)) - { - if value.is_any_tree() { - let mut sub_path = q.clone(); - sub_path.push(key.to_vec()); - queue.push(sub_path.clone()); - result.push(sub_path); - } + let storage = self + .db + .get_transactional_storage_context(subtree_path, None, tx.as_ref()) + .unwrap_add_cost(&mut cost); + + let mut raw_iter = Element::iterator(storage.raw_iter()).unwrap_add_cost(&mut cost); + while let Some((key, value)) = + cost_return_on_error!(&mut cost, raw_iter.next_element(grove_version)) + { + if value.is_any_tree() { + let mut sub_path = q.clone(); + sub_path.push(key.to_vec()); + queue.push(sub_path.clone()); + result.push(sub_path); } - }) + } } Ok(result).wrap_with_cost(cost) } diff --git a/grovedb/src/operations/delete/average_case.rs b/grovedb/src/operations/delete/average_case.rs index 986f2b90a..56162e8e1 100644 --- a/grovedb/src/operations/delete/average_case.rs +++ b/grovedb/src/operations/delete/average_case.rs @@ -67,11 +67,11 @@ impl GroveDb { estimated_element_size, is_sum_tree, ) = cost_return_on_error_no_add!( - &cost, + cost, if height == path_len - 1 { if let Some(layer_info) = estimated_layer_info.get(height as u64) { let estimated_value_len = cost_return_on_error_no_add!( - &cost, + cost, layer_info .estimated_layer_sizes .value_with_feature_and_flags_size() @@ -96,7 +96,7 @@ impl GroveDb { used_path = smaller_path; if let Some(layer_info) = estimated_layer_info.get(height as u64) { let estimated_value_len = cost_return_on_error_no_add!( - &cost, + cost, layer_info .estimated_layer_sizes .subtree_with_feature_and_flags_size() @@ -158,7 +158,7 @@ impl GroveDb { if validate { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_average_case_get_merk_at_path::( &mut cost, path, @@ -170,7 +170,7 @@ impl GroveDb { } if check_if_tree { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_average_case_get_raw_cost::( &mut cost, path, diff --git a/grovedb/src/operations/delete/delete_up_tree.rs b/grovedb/src/operations/delete/delete_up_tree.rs index 7ecfce83e..3bf5324d0 100644 --- a/grovedb/src/operations/delete/delete_up_tree.rs +++ b/grovedb/src/operations/delete/delete_up_tree.rs @@ -6,9 +6,7 @@ use grovedb_costs::{ CostResult, CostsExt, OperationCost, }; use grovedb_path::SubtreePath; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use crate::{ batch::QualifiedGroveDbOp, operations::delete::DeleteOptions, ElementFlags, Error, GroveDb, @@ -138,7 +136,7 @@ impl GroveDb { ); let ops = cost_return_on_error_no_add!( - &cost, + cost, if let Some(stop_path_height) = options.stop_path_height { maybe_ops.ok_or_else(|| { Error::DeleteUpTreeStopHeightMoreThanInitialPathSize(format!( diff --git a/grovedb/src/operations/delete/mod.rs b/grovedb/src/operations/delete/mod.rs index 9244c60be..79ceb88ba 100644 --- a/grovedb/src/operations/delete/mod.rs +++ b/grovedb/src/operations/delete/mod.rs @@ -2,44 +2,32 @@ #[cfg(feature = "estimated_costs")] mod average_case; -#[cfg(feature = "full")] mod delete_up_tree; #[cfg(feature = "estimated_costs")] mod worst_case; -#[cfg(feature = "full")] use std::collections::{BTreeSet, HashMap}; -#[cfg(feature = "full")] pub use delete_up_tree::DeleteUpTreeOptions; -#[cfg(feature = "full")] use grovedb_costs::{ cost_return_on_error, - storage_cost::removal::{StorageRemovedBytes, StorageRemovedBytes::BasicStorageRemoval}, + storage_cost::removal::StorageRemovedBytes::{self, BasicStorageRemoval}, CostResult, CostsExt, OperationCost, }; -use grovedb_merk::{proofs::Query, KVIterator}; -#[cfg(feature = "full")] -use grovedb_merk::{Error as MerkError, Merk, MerkOptions}; +use grovedb_merk::{proofs::Query, Error as MerkError, KVIterator, Merk, MerkOptions}; use grovedb_path::SubtreePath; -#[cfg(feature = "full")] use grovedb_storage::{ - rocksdb_storage::{PrefixedRocksDbStorageContext, PrefixedRocksDbTransactionContext}, - Storage, StorageBatch, StorageContext, -}; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, + rocksdb_storage::PrefixedRocksDbTransactionContext, Storage, StorageBatch, StorageContext, }; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; -#[cfg(feature = "full")] use crate::{ batch::{GroveOp, QualifiedGroveDbOp}, - util::storage_context_with_parent_optional_tx, + raw_decode, + util::TxRef, Element, ElementFlags, Error, GroveDb, Transaction, TransactionArg, }; -use crate::{raw_decode, util::merk_optional_tx_path_not_empty}; -#[cfg(feature = "full")] #[derive(Clone)] /// Clear options pub struct ClearOptions { @@ -52,7 +40,6 @@ pub struct ClearOptions { pub trying_to_clear_with_subtrees_returns_error: bool, } -#[cfg(feature = "full")] impl Default for ClearOptions { fn default() -> Self { ClearOptions { @@ -63,7 +50,6 @@ impl Default for ClearOptions { } } -#[cfg(feature = "full")] #[derive(Clone)] /// Delete options pub struct DeleteOptions { @@ -77,7 +63,6 @@ pub struct DeleteOptions { pub validate_tree_at_path_exists: bool, } -#[cfg(feature = "full")] impl Default for DeleteOptions { fn default() -> Self { DeleteOptions { @@ -89,7 +74,6 @@ impl Default for DeleteOptions { } } -#[cfg(feature = "full")] impl DeleteOptions { fn as_merk_options(&self) -> MerkOptions { MerkOptions { @@ -98,7 +82,6 @@ impl DeleteOptions { } } -#[cfg(feature = "full")] impl GroveDb { /// Delete an element at a specified subtree path and key. pub fn delete<'b, B, P>( @@ -121,12 +104,14 @@ impl GroveDb { let options = options.unwrap_or_default(); let batch = StorageBatch::new(); + let tx = TxRef::new(&self.db, transaction); + let collect_costs = self .delete_internal( path.into(), key, &options, - transaction, + tx.as_ref(), &mut |_, removed_key_bytes, removed_value_bytes| { Ok(( BasicStorageRemoval(removed_key_bytes), @@ -138,11 +123,14 @@ impl GroveDb { ) .map_ok(|_| ()); - collect_costs.flat_map_ok(|_| { - self.db - .commit_multi_context_batch(batch, transaction) - .map_err(Into::into) - }) + collect_costs + .flat_map_ok(|_| { + self.db + .commit_multi_context_batch(batch, transaction) + .map_err(Into::into) + .map_ok(|_| tx.commit_local()) + }) + .flatten() } /// Delete all elements in a specified subtree @@ -158,8 +146,15 @@ impl GroveDb { B: AsRef<[u8]> + 'b, P: Into>, { - self.clear_subtree_with_costs(path, options, transaction, grove_version) - .unwrap() + let tx = TxRef::new(&self.db, transaction); + if self + .clear_subtree_with_costs(path, options, tx.as_ref(), grove_version) + .unwrap()? + { + tx.commit_local()?; + return Ok(true); + } + Ok(false) } /// Delete all elements in a specified subtree and get back costs @@ -170,7 +165,7 @@ impl GroveDb { &self, path: P, options: Option, - transaction: TransactionArg, + transaction: &Transaction, grove_version: &GroveVersion, ) -> CostResult where @@ -192,114 +187,44 @@ impl GroveDb { let options = options.unwrap_or_default(); - if let Some(transaction) = transaction { - let mut merk_to_clear = cost_return_on_error!( - &mut cost, - self.open_transactional_merk_at_path( - subtree_path.clone(), - transaction, - Some(&batch), - grove_version, - ) - ); - - if options.check_for_subtrees { - let mut all_query = Query::new(); - all_query.insert_all(); - - let mut element_iterator = - KVIterator::new(merk_to_clear.storage.raw_iter(), &all_query).unwrap(); - - // delete all nested subtrees - while let Some((key, element_value)) = - element_iterator.next_kv().unwrap_add_cost(&mut cost) - { - let element = raw_decode(&element_value, grove_version).unwrap(); - if element.is_any_tree() { - if options.allow_deleting_subtrees { - cost_return_on_error!( - &mut cost, - self.delete( - subtree_path.clone(), - key.as_slice(), - Some(DeleteOptions { - allow_deleting_non_empty_trees: true, - deleting_non_empty_trees_returns_error: false, - ..Default::default() - }), - Some(transaction), - grove_version, - ) - ); - } else if options.trying_to_clear_with_subtrees_returns_error { - return Err(Error::ClearingTreeWithSubtreesNotAllowed( - "options do not allow to clear this merk tree as it contains \ - subtrees", - )) - .wrap_with_cost(cost); - } else { - return Ok(false).wrap_with_cost(cost); - } - } - } - } - - // delete non subtree values - cost_return_on_error!(&mut cost, merk_to_clear.clear().map_err(Error::MerkError)); - - // propagate changes - let mut merk_cache: HashMap, Merk> = - HashMap::default(); - merk_cache.insert(subtree_path.clone(), merk_to_clear); - cost_return_on_error!( - &mut cost, - self.propagate_changes_with_transaction( - merk_cache, - subtree_path.clone(), - transaction, - &batch, - grove_version, - ) - ); - } else { - let mut merk_to_clear = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path( - subtree_path.clone(), - Some(&batch), - grove_version - ) - ); + let mut merk_to_clear = cost_return_on_error!( + &mut cost, + self.open_transactional_merk_at_path( + subtree_path.clone(), + transaction, + Some(&batch), + grove_version, + ) + ); - if options.check_for_subtrees { - let mut all_query = Query::new(); - all_query.insert_all(); + if options.check_for_subtrees { + let mut all_query = Query::new(); + all_query.insert_all(); - let mut element_iterator = - KVIterator::new(merk_to_clear.storage.raw_iter(), &all_query).unwrap(); + let mut element_iterator = + KVIterator::new(merk_to_clear.storage.raw_iter(), &all_query).unwrap(); - // delete all nested subtrees - while let Some((key, element_value)) = - element_iterator.next_kv().unwrap_add_cost(&mut cost) - { - let element = raw_decode(&element_value, grove_version).unwrap(); + // delete all nested subtrees + while let Some((key, element_value)) = + element_iterator.next_kv().unwrap_add_cost(&mut cost) + { + let element = raw_decode(&element_value, grove_version).unwrap(); + if element.is_any_tree() { if options.allow_deleting_subtrees { - if element.is_any_tree() { - cost_return_on_error!( - &mut cost, - self.delete( - subtree_path.clone(), - key.as_slice(), - Some(DeleteOptions { - allow_deleting_non_empty_trees: true, - deleting_non_empty_trees_returns_error: false, - ..Default::default() - }), - None, - grove_version, - ) - ); - } + cost_return_on_error!( + &mut cost, + self.delete( + subtree_path.clone(), + key.as_slice(), + Some(DeleteOptions { + allow_deleting_non_empty_trees: true, + deleting_non_empty_trees_returns_error: false, + ..Default::default() + }), + Some(transaction), + grove_version, + ) + ); } else if options.trying_to_clear_with_subtrees_returns_error { return Err(Error::ClearingTreeWithSubtreesNotAllowed( "options do not allow to clear this merk tree as it contains subtrees", @@ -310,29 +235,30 @@ impl GroveDb { } } } + } - // delete non subtree values - cost_return_on_error!(&mut cost, merk_to_clear.clear().map_err(Error::MerkError)); + // delete non subtree values + cost_return_on_error!(&mut cost, merk_to_clear.clear().map_err(Error::MerkError)); - // propagate changes - let mut merk_cache: HashMap, Merk> = - HashMap::default(); - merk_cache.insert(subtree_path.clone(), merk_to_clear); - cost_return_on_error!( - &mut cost, - self.propagate_changes_without_transaction( - merk_cache, - subtree_path.clone(), - &batch, - grove_version, - ) - ); - } + // propagate changes + let mut merk_cache: HashMap, Merk> = + HashMap::default(); + merk_cache.insert(subtree_path.clone(), merk_to_clear); + cost_return_on_error!( + &mut cost, + self.propagate_changes_with_transaction( + merk_cache, + subtree_path.clone(), + transaction, + &batch, + grove_version, + ) + ); cost_return_on_error!( &mut cost, self.db - .commit_multi_context_batch(batch, transaction) + .commit_multi_context_batch(batch, Some(transaction)) .map_err(Into::into) ); @@ -368,12 +294,14 @@ impl GroveDb { let options = options.unwrap_or_default(); let batch = StorageBatch::new(); + let tx = TxRef::new(&self.db, transaction); + let collect_costs = self .delete_internal( path, key, &options, - transaction, + tx.as_ref(), &mut |value, removed_key_bytes, removed_value_bytes| { let mut element = Element::deserialize(value.as_slice(), grove_version) .map_err(|e| MerkError::ClientCorruptionError(e.to_string()))?; @@ -398,8 +326,10 @@ impl GroveDb { collect_costs.flat_map_ok(|_| { self.db - .commit_multi_context_batch(batch, transaction) + .commit_multi_context_batch(batch, Some(tx.as_ref())) + .map_ok(|_| tx.commit_local()) .map_err(Into::into) + .flatten() }) } @@ -480,11 +410,13 @@ impl GroveDb { ..Default::default() }; + let tx = TxRef::new(&self.db, transaction); + self.delete_internal( path, key, &options, - transaction, + tx.as_ref(), &mut |value, removed_key_bytes, removed_value_bytes| { let mut element = Element::deserialize(value.as_slice(), grove_version) .map_err(|e| MerkError::ClientCorruptionError(e.to_string()))?; @@ -503,6 +435,11 @@ impl GroveDb { batch, grove_version, ) + .map_ok(|r| { + tx.commit_local()?; + Ok(r) + }) + .flatten() } /// Delete operation for delete internal @@ -527,6 +464,8 @@ impl GroveDb { let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); + if path.is_root() { // Attempt to delete a root tree leaf Err(Error::InvalidPath( @@ -559,7 +498,7 @@ impl GroveDb { Some(x) => x, }; - if is_subtree { + let result = if is_subtree { let subtree_merk_path = path.derive_owned_with_child(key); let subtree_merk_path_vec = subtree_merk_path.to_vec(); let batch_deleted_keys = current_batch_operations @@ -577,21 +516,20 @@ impl GroveDb { _ => None, }) .collect::>(); - let mut is_empty = merk_optional_tx_path_not_empty!( + let subtree = cost_return_on_error!( &mut cost, - self.db, - SubtreePath::from(&subtree_merk_path), - None, - transaction, - subtree, - grove_version, - { - subtree - .is_empty_tree_except(batch_deleted_keys) - .unwrap_add_cost(&mut cost) - } + self.open_transactional_merk_at_path( + SubtreePath::from(&subtree_merk_path), + tx.as_ref(), + None, + grove_version, + ) ); + let mut is_empty = subtree + .is_empty_tree_except(batch_deleted_keys) + .unwrap_add_cost(&mut cost); + // If there is any current batch operation that is inserting something in this // tree then it is not empty either is_empty &= !current_batch_operations.iter().any(|op| match op.op { @@ -627,50 +565,18 @@ impl GroveDb { key.to_vec(), ))) .wrap_with_cost(cost) - } - } - } + }; - fn delete_internal>( - &self, - path: SubtreePath, - key: &[u8], - options: &DeleteOptions, - transaction: TransactionArg, - sectioned_removal: &mut impl FnMut( - &Vec, - u32, - u32, - ) -> Result< - (StorageRemovedBytes, StorageRemovedBytes), - MerkError, - >, - batch: &StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult { - if let Some(transaction) = transaction { - self.delete_internal_on_transaction( - path, - key, - options, - transaction, - sectioned_removal, - batch, - grove_version, - ) - } else { - self.delete_internal_without_transaction( - path, - key, - options, - sectioned_removal, - batch, - grove_version, - ) + result + .map_ok(|r| { + tx.commit_local()?; + Ok(r) + }) + .flatten() } } - fn delete_internal_on_transaction>( + fn delete_internal>( &self, path: SubtreePath, key: &[u8], @@ -799,11 +705,11 @@ impl GroveDb { merk_cache.insert(path.clone(), merk_to_delete_tree_from); cost_return_on_error!( &mut cost, - self.propagate_changes_with_batch_transaction( - batch, + self.propagate_changes_with_transaction( merk_cache, - &path, + path, transaction, + batch, grove_version, ) ); @@ -867,134 +773,8 @@ impl GroveDb { Ok(true).wrap_with_cost(cost) } - - fn delete_internal_without_transaction>( - &self, - path: SubtreePath, - key: &[u8], - options: &DeleteOptions, - sectioned_removal: &mut impl FnMut( - &Vec, - u32, - u32, - ) -> Result< - (StorageRemovedBytes, StorageRemovedBytes), - MerkError, - >, - batch: &StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult { - check_grovedb_v0_with_cost!( - "delete_internal_without_transaction", - grove_version - .grovedb_versions - .operations - .delete - .delete_internal_without_transaction - ); - - let mut cost = OperationCost::default(); - - let element = cost_return_on_error!( - &mut cost, - self.get_raw(path.clone(), key.as_ref(), None, grove_version) - ); - let mut merk_cache: HashMap, Merk> = - HashMap::default(); - let mut subtree_to_delete_from = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path(path.clone(), Some(batch), grove_version) - ); - let uses_sum_tree = subtree_to_delete_from.is_sum_tree; - if element.is_any_tree() { - let subtree_merk_path = path.derive_owned_with_child(key); - let subtree_of_tree_we_are_deleting = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path( - SubtreePath::from(&subtree_merk_path), - Some(batch), - grove_version, - ) - ); - let is_empty = subtree_of_tree_we_are_deleting - .is_empty_tree() - .unwrap_add_cost(&mut cost); - - if !options.allow_deleting_non_empty_trees && !is_empty { - return if options.deleting_non_empty_trees_returns_error { - Err(Error::DeletingNonEmptyTree( - "trying to do a delete operation for a non empty tree, but options not \ - allowing this", - )) - .wrap_with_cost(cost) - } else { - Ok(false).wrap_with_cost(cost) - }; - } else { - if !is_empty { - let subtrees_paths = cost_return_on_error!( - &mut cost, - self.find_subtrees( - &SubtreePath::from(&subtree_merk_path), - None, - grove_version - ) - ); - // TODO: dumb traversal should not be tolerated - for subtree_path in subtrees_paths.into_iter().rev() { - let p: SubtreePath<_> = subtree_path.as_slice().into(); - let mut inner_subtree_to_delete_from = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path(p, Some(batch), grove_version) - ); - cost_return_on_error!( - &mut cost, - inner_subtree_to_delete_from.clear().map_err(|e| { - Error::CorruptedData(format!( - "unable to cleanup tree from storage: {e}", - )) - }) - ); - } - } - cost_return_on_error!( - &mut cost, - Element::delete_with_sectioned_removal_bytes( - &mut subtree_to_delete_from, - key, - Some(options.as_merk_options()), - true, - uses_sum_tree, - sectioned_removal, - grove_version, - ) - ); - } - } else { - cost_return_on_error!( - &mut cost, - Element::delete_with_sectioned_removal_bytes( - &mut subtree_to_delete_from, - key, - Some(options.as_merk_options()), - false, - uses_sum_tree, - sectioned_removal, - grove_version, - ) - ); - } - merk_cache.insert(path.clone(), subtree_to_delete_from); - cost_return_on_error!( - &mut cost, - self.propagate_changes_without_transaction(merk_cache, path, batch, grove_version) - ); - - Ok(true).wrap_with_cost(cost) - } } -#[cfg(feature = "full")] #[cfg(test)] mod tests { use grovedb_costs::{ @@ -1051,7 +831,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); // assert_eq!(db.subtrees.len().unwrap(), 3); // TEST_LEAF, ANOTHER_TEST_LEAF // TEST_LEAF.key4 stay @@ -1120,7 +900,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); transaction.commit().expect("cannot commit transaction"); assert!(matches!( @@ -1242,7 +1022,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); assert!(matches!( @@ -1363,7 +1143,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); assert!(matches!( @@ -1457,7 +1237,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); transaction.commit().expect("cannot commit transaction"); assert!(matches!( @@ -1542,7 +1322,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); assert!(matches!( db.get([TEST_LEAF].as_ref(), b"key1", None, grove_version) @@ -1885,9 +1665,13 @@ mod tests { .unwrap() .unwrap(); assert!(!matches!(key1_tree, Element::Tree(None, _))); + + let tx = db.start_transaction(); + let key1_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, None, grove_version, ) @@ -1941,7 +1725,7 @@ mod tests { grove_version ) .unwrap(), - Err(Error::PathParentLayerNotFound(_)) + Err(Error::InvalidParentLayerPath(_)) )); let key1_tree = db .get([TEST_LEAF].as_ref(), b"key1", None, grove_version) @@ -1950,8 +1734,9 @@ mod tests { assert!(matches!(key1_tree, Element::Tree(None, _))); let key1_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, None, grove_version, ) diff --git a/grovedb/src/operations/delete/worst_case.rs b/grovedb/src/operations/delete/worst_case.rs index 8533cde55..41f0d4000 100644 --- a/grovedb/src/operations/delete/worst_case.rs +++ b/grovedb/src/operations/delete/worst_case.rs @@ -7,9 +7,7 @@ use grovedb_merk::{ estimated_costs::worst_case_costs::add_worst_case_cost_for_is_empty_tree_except, tree::kv::KV, }; use grovedb_storage::{worst_case_costs::WorstKeyLength, Storage}; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use intmap::IntMap; use crate::{ @@ -61,7 +59,7 @@ impl GroveDb { max_element_size, is_sum_tree, ) = cost_return_on_error_no_add!( - &cost, + cost, if height == path_len { if let Some((is_in_sum_tree, _)) = intermediate_tree_info.get(height as u64) { @@ -140,7 +138,7 @@ impl GroveDb { if validate { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_worst_case_get_merk_at_path::( &mut cost, path, @@ -151,7 +149,7 @@ impl GroveDb { } if check_if_tree { cost_return_on_error_no_add!( - &cost, + cost, GroveDb::add_worst_case_get_raw_cost::( &mut cost, path, diff --git a/grovedb/src/operations/get/average_case.rs b/grovedb/src/operations/get/average_case.rs index aca4426df..8ba36ea0b 100644 --- a/grovedb/src/operations/get/average_case.rs +++ b/grovedb/src/operations/get/average_case.rs @@ -4,7 +4,7 @@ use grovedb_costs::OperationCost; #[cfg(feature = "full")] use grovedb_storage::rocksdb_storage::RocksDbStorage; -use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; +use grovedb_version::{check_grovedb_v0, version::GroveVersion}; use crate::Error; #[cfg(feature = "full")] diff --git a/grovedb/src/operations/get/mod.rs b/grovedb/src/operations/get/mod.rs index b62896996..c912ce076 100644 --- a/grovedb/src/operations/get/mod.rs +++ b/grovedb/src/operations/get/mod.rs @@ -2,38 +2,29 @@ #[cfg(feature = "estimated_costs")] mod average_case; -#[cfg(feature = "full")] mod query; -#[cfg(feature = "full")] pub use query::QueryItemOrSumReturnType; #[cfg(feature = "estimated_costs")] mod worst_case; -#[cfg(feature = "full")] use std::collections::HashSet; -use grovedb_costs::cost_return_on_error_no_add; -#[cfg(feature = "full")] -use grovedb_costs::{cost_return_on_error, CostResult, CostsExt, OperationCost}; -use grovedb_path::SubtreePath; -#[cfg(feature = "full")] -use grovedb_storage::StorageContext; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, +use grovedb_costs::{ + cost_return_on_error, cost_return_on_error_no_add, CostResult, CostsExt, OperationCost, }; +use grovedb_path::SubtreePath; +use grovedb_storage::{Storage, StorageContext}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; -#[cfg(feature = "full")] use crate::{ reference_path::{path_from_reference_path_type, path_from_reference_qualified_path_type}, - util::storage_context_optional_tx, + util::TxRef, Element, Error, GroveDb, Transaction, TransactionArg, }; -#[cfg(feature = "full")] /// Limit of possible indirections pub const MAX_REFERENCE_HOPS: usize = 10; -#[cfg(feature = "full")] impl GroveDb { /// Get an element from the backing store /// Merk Caching is on by default @@ -74,6 +65,7 @@ impl GroveDb { ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); match cost_return_on_error!( &mut cost, @@ -81,7 +73,7 @@ impl GroveDb { path.clone(), key, allow_cache, - transaction, + Some(tx.as_ref()), grove_version ) ) { @@ -94,7 +86,7 @@ impl GroveDb { self.follow_reference( path_owned.as_slice().into(), allow_cache, - transaction, + tx.as_ref(), grove_version, ) .add_cost(cost) @@ -106,11 +98,11 @@ impl GroveDb { /// Return the Element that a reference points to. /// If the reference points to another reference, keep following until /// base element is reached. - pub fn follow_reference>( + pub(crate) fn follow_reference>( &self, path: SubtreePath, allow_cache: bool, - transaction: TransactionArg, + transaction: &Transaction, grove_version: &GroveVersion, ) -> CostResult { check_grovedb_v0_with_cost!( @@ -141,11 +133,11 @@ impl GroveDb { path_slice.into(), key, allow_cache, - transaction, + Some(transaction), grove_version ) .map_err(|e| match e { - Error::PathParentLayerNotFound(p) => { + Error::InvalidParentLayerPath(p) => { Error::CorruptedReferencePathParentLayerNotFound(p) } Error::PathKeyNotFound(p) => { @@ -211,17 +203,15 @@ impl GroveDb { .get_raw_caching_optional ); - if let Some(transaction) = transaction { - self.get_raw_on_transaction_caching_optional( - path, - key, - allow_cache, - transaction, - grove_version, - ) - } else { - self.get_raw_without_transaction_caching_optional(path, key, allow_cache, grove_version) - } + let tx = TxRef::new(&self.db, transaction); + + self.get_raw_on_transaction_caching_optional( + path, + key, + allow_cache, + tx.as_ref(), + grove_version, + ) } /// Get Element at specified path and key @@ -264,22 +254,15 @@ impl GroveDb { .get_raw_optional_caching_optional ); - if let Some(transaction) = transaction { - self.get_raw_optional_on_transaction_caching_optional( - path, - key, - allow_cache, - transaction, - grove_version, - ) - } else { - self.get_raw_optional_without_transaction_caching_optional( - path, - key, - allow_cache, - grove_version, - ) - } + let tx = TxRef::new(&self.db, transaction); + + self.get_raw_optional_on_transaction_caching_optional( + path, + key, + allow_cache, + tx.as_ref(), + grove_version, + ) } /// Get tree item without following references @@ -296,12 +279,6 @@ impl GroveDb { let merk_to_get_from = cost_return_on_error!( &mut cost, self.open_transactional_merk_at_path(path, transaction, None, grove_version) - .map_err(|e| match e { - Error::InvalidParentLayerPath(s) => { - Error::PathParentLayerNotFound(s) - } - _ => e, - }) ); Element::get(&merk_to_get_from, key, allow_cache, grove_version).add_cost(cost) @@ -319,75 +296,12 @@ impl GroveDb { let mut cost = OperationCost::default(); let merk_result = self .open_transactional_merk_at_path(path, transaction, None, grove_version) - .map_err(|e| match e { - Error::InvalidParentLayerPath(s) => Error::PathParentLayerNotFound(s), - _ => e, - }) - .unwrap_add_cost(&mut cost); - let merk = cost_return_on_error_no_add!( - &cost, - match merk_result { - Ok(result) => Ok(Some(result)), - Err(Error::PathParentLayerNotFound(_)) | Err(Error::InvalidParentLayerPath(_)) => - Ok(None), - Err(e) => Err(e), - } - ); - - if let Some(merk_to_get_from) = merk { - Element::get_optional(&merk_to_get_from, key, allow_cache, grove_version).add_cost(cost) - } else { - Ok(None).wrap_with_cost(cost) - } - } - - /// Get tree item without following references - pub(crate) fn get_raw_without_transaction_caching_optional>( - &self, - path: SubtreePath, - key: &[u8], - allow_cache: bool, - grove_version: &GroveVersion, - ) -> CostResult { - let mut cost = OperationCost::default(); - - let merk_to_get_from = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path(path, None, grove_version) - .map_err(|e| match e { - Error::InvalidParentLayerPath(s) => { - Error::PathParentLayerNotFound(s) - } - _ => e, - }) - ); - - Element::get(&merk_to_get_from, key, allow_cache, grove_version).add_cost(cost) - } - - /// Get tree item without following references - pub(crate) fn get_raw_optional_without_transaction_caching_optional>( - &self, - path: SubtreePath, - key: &[u8], - allow_cache: bool, - grove_version: &GroveVersion, - ) -> CostResult, Error> { - let mut cost = OperationCost::default(); - - let merk_result = self - .open_non_transactional_merk_at_path(path, None, grove_version) - .map_err(|e| match e { - Error::InvalidParentLayerPath(s) => Error::PathParentLayerNotFound(s), - _ => e, - }) .unwrap_add_cost(&mut cost); let merk = cost_return_on_error_no_add!( - &cost, + cost, match merk_result { Ok(result) => Ok(Some(result)), - Err(Error::PathParentLayerNotFound(_)) | Err(Error::InvalidParentLayerPath(_)) => - Ok(None), + Err(Error::InvalidParentLayerPath(_)) => Ok(None), Err(e) => Err(e), } ); @@ -417,23 +331,25 @@ impl GroveDb { grove_version.grovedb_versions.operations.get.has_raw ); + let tx = TxRef::new(&self.db, transaction); + // Merk's items should be written into data storage and checked accordingly - storage_context_optional_tx!(self.db, path.into(), None, transaction, storage, { - storage.flat_map(|s| s.get(key).map_err(|e| e.into()).map_ok(|x| x.is_some())) - }) + self.db + .get_transactional_storage_context(path.into(), None, tx.as_ref()) + .flat_map(|s| s.get(key).map_err(|e| e.into()).map_ok(|x| x.is_some())) } fn check_subtree_exists>( &self, path: SubtreePath, - transaction: TransactionArg, + transaction: &Transaction, error_fn: impl FnOnce() -> Error, grove_version: &GroveVersion, ) -> CostResult<(), Error> { let mut cost = OperationCost::default(); if let Some((parent_path, parent_key)) = path.derive_parent() { - let element = if let Some(transaction) = transaction { + let element = { let merk_to_get_from = cost_return_on_error!( &mut cost, self.open_transactional_merk_at_path( @@ -444,13 +360,6 @@ impl GroveDb { ) ); - Element::get(&merk_to_get_from, parent_key, true, grove_version) - } else { - let merk_to_get_from = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path(parent_path, None, grove_version) - ); - Element::get(&merk_to_get_from, parent_key, true, grove_version) } .unwrap_add_cost(&mut cost); @@ -474,9 +383,11 @@ impl GroveDb { where B: AsRef<[u8]> + 'b, { + let tx = TxRef::new(&self.db, transaction); + self.check_subtree_exists( path.clone(), - transaction, + tx.as_ref(), || { Error::PathNotFound(format!( "subtree doesn't exist at path {:?}", @@ -506,9 +417,11 @@ impl GroveDb { .check_subtree_exists_invalid_path ); + let tx = TxRef::new(&self.db, transaction); + self.check_subtree_exists( path, - transaction, + tx.as_ref(), || Error::InvalidPath("subtree doesn't exist".to_owned()), grove_version, ) diff --git a/grovedb/src/operations/get/query.rs b/grovedb/src/operations/get/query.rs index 81046dbfc..6f7258082 100644 --- a/grovedb/src/operations/get/query.rs +++ b/grovedb/src/operations/get/query.rs @@ -5,9 +5,7 @@ use grovedb_costs::cost_return_on_error_default; use grovedb_costs::{ cost_return_on_error, cost_return_on_error_no_add, CostResult, CostsExt, OperationCost, }; -use grovedb_version::{ - check_grovedb_v0, check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0, check_grovedb_v0_with_cost, version::GroveVersion}; #[cfg(feature = "full")] use integer_encoding::VarInt; @@ -15,7 +13,7 @@ use integer_encoding::VarInt; use crate::element::SumValue; use crate::{ element::QueryOptions, operations::proof::ProveOptions, - query_result_type::PathKeyOptionalElementTrio, + query_result_type::PathKeyOptionalElementTrio, util::TxRef, Transaction, }; #[cfg(feature = "full")] use crate::{ @@ -56,6 +54,7 @@ impl GroveDb { ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); let elements = cost_return_on_error!( &mut cost, @@ -83,7 +82,7 @@ impl GroveDb { .follow_reference( absolute_path.as_slice().into(), allow_cache, - transaction, + tx.as_ref(), grove_version, ) .unwrap_add_cost(&mut cost)?; @@ -133,7 +132,7 @@ where { let mut cost = OperationCost::default(); let query = cost_return_on_error_no_add!( - &cost, + cost, PathQuery::merge(path_queries.to_vec(), grove_version) ); let (result, _) = cost_return_on_error!( @@ -182,7 +181,7 @@ where { element: Element, allow_cache: bool, cost: &mut OperationCost, - transaction: TransactionArg, + transaction: &Transaction, grove_version: &GroveVersion, ) -> Result { check_grovedb_v0!( @@ -243,6 +242,7 @@ where { grove_version.grovedb_versions.operations.query.query ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); let (elements, skipped) = cost_return_on_error!( &mut cost, @@ -261,12 +261,12 @@ where { .into_iterator() .map(|result_item| { result_item.map_element(|element| { - self.follow_element(element, allow_cache, &mut cost, transaction, grove_version) + self.follow_element(element, allow_cache, &mut cost, tx.as_ref(), grove_version) }) }) .collect::, Error>>(); - let results = cost_return_on_error_no_add!(&cost, results_wrapped); + let results = cost_return_on_error_no_add!(cost, results_wrapped); Ok((QueryResultElements { elements: results }, skipped)).wrap_with_cost(cost) } @@ -290,6 +290,7 @@ where { .query_item_value ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); let (elements, skipped) = cost_return_on_error!( &mut cost, @@ -321,7 +322,7 @@ where { .follow_reference( absolute_path.as_slice().into(), allow_cache, - transaction, + tx.as_ref(), grove_version, ) .unwrap_add_cost(&mut cost)?; @@ -352,7 +353,7 @@ where { }) .collect::>, Error>>(); - let results = cost_return_on_error_no_add!(&cost, results_wrapped); + let results = cost_return_on_error_no_add!(cost, results_wrapped); Ok((results, skipped)).wrap_with_cost(cost) } @@ -376,6 +377,7 @@ where { .query_item_value_or_sum ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); let (elements, skipped) = cost_return_on_error!( &mut cost, @@ -407,7 +409,7 @@ where { .follow_reference( absolute_path.as_slice().into(), allow_cache, - transaction, + tx.as_ref(), grove_version, ) .unwrap_add_cost(&mut cost)?; @@ -451,7 +453,7 @@ where { }) .collect::, Error>>(); - let results = cost_return_on_error_no_add!(&cost, results_wrapped); + let results = cost_return_on_error_no_add!(cost, results_wrapped); Ok((results, skipped)).wrap_with_cost(cost) } @@ -470,6 +472,7 @@ where { grove_version.grovedb_versions.operations.query.query_sums ); let mut cost = OperationCost::default(); + let tx = TxRef::new(&self.db, transaction); let (elements, skipped) = cost_return_on_error!( &mut cost, @@ -501,7 +504,7 @@ where { .follow_reference( absolute_path.as_slice().into(), allow_cache, - transaction, + tx.as_ref(), grove_version, ) .unwrap_add_cost(&mut cost)?; @@ -534,7 +537,7 @@ where { }) .collect::, Error>>(); - let results = cost_return_on_error_no_add!(&cost, results_wrapped); + let results = cost_return_on_error_no_add!(cost, results_wrapped); Ok((results, skipped)).wrap_with_cost(cost) } @@ -599,7 +602,7 @@ where { let mut cost = OperationCost::default(); let terminal_keys = cost_return_on_error_no_add!( - &cost, + cost, path_query.terminal_keys(max_results, grove_version) ); @@ -658,7 +661,7 @@ where { let mut cost = OperationCost::default(); let terminal_keys = cost_return_on_error_no_add!( - &cost, + cost, path_query.terminal_keys(max_results, grove_version) ); diff --git a/grovedb/src/operations/get/worst_case.rs b/grovedb/src/operations/get/worst_case.rs index 7554a9111..76efa72fb 100644 --- a/grovedb/src/operations/get/worst_case.rs +++ b/grovedb/src/operations/get/worst_case.rs @@ -4,7 +4,7 @@ use grovedb_costs::OperationCost; #[cfg(feature = "full")] use grovedb_storage::rocksdb_storage::RocksDbStorage; -use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; +use grovedb_version::{check_grovedb_v0, version::GroveVersion}; use crate::Error; #[cfg(feature = "full")] diff --git a/grovedb/src/operations/insert/mod.rs b/grovedb/src/operations/insert/mod.rs index 5926fedd2..0c5f03e6e 100644 --- a/grovedb/src/operations/insert/mod.rs +++ b/grovedb/src/operations/insert/mod.rs @@ -1,31 +1,20 @@ //! Insert operations -#[cfg(feature = "full")] -use std::{collections::HashMap, option::Option::None}; +use std::option::Option::None; -#[cfg(feature = "full")] use grovedb_costs::{ cost_return_on_error, cost_return_on_error_no_add, CostResult, CostsExt, OperationCost, }; -#[cfg(feature = "full")] -use grovedb_merk::{tree::NULL_HASH, Merk, MerkOptions}; +use grovedb_merk::{tree::NULL_HASH, MerkOptions}; use grovedb_path::SubtreePath; -#[cfg(feature = "full")] -use grovedb_storage::rocksdb_storage::{ - PrefixedRocksDbStorageContext, PrefixedRocksDbTransactionContext, -}; -use grovedb_storage::{Storage, StorageBatch}; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_storage::Storage; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; -#[cfg(feature = "full")] use crate::{ - reference_path::path_from_reference_path_type, Element, Error, GroveDb, Transaction, - TransactionArg, + merk_cache::{MerkCache, MerkHandle}, + util::{self, TxRef}, + Element, Error, GroveDb, TransactionArg, }; - -#[cfg(feature = "full")] #[derive(Clone)] /// Insert options pub struct InsertOptions { @@ -37,7 +26,6 @@ pub struct InsertOptions { pub base_root_storage_is_free: bool, } -#[cfg(feature = "full")] impl Default for InsertOptions { fn default() -> Self { InsertOptions { @@ -48,20 +36,18 @@ impl Default for InsertOptions { } } -#[cfg(feature = "full")] impl InsertOptions { fn checks_for_override(&self) -> bool { self.validate_insertion_does_not_override_tree || self.validate_insertion_does_not_override } - fn as_merk_options(&self) -> MerkOptions { + pub(crate) fn as_merk_options(&self) -> MerkOptions { MerkOptions { base_root_storage_is_free: self.base_root_storage_is_free, } } } -#[cfg(feature = "full")] impl GroveDb { /// Insert a GroveDB element given a path to the subtree and the key to /// insert at @@ -83,130 +69,29 @@ impl GroveDb { grove_version.grovedb_versions.operations.insert.insert ); - let subtree_path: SubtreePath = path.into(); - let batch = StorageBatch::new(); - - let collect_costs = if let Some(transaction) = transaction { - self.insert_on_transaction( - subtree_path, - key, - element, - options.unwrap_or_default(), - transaction, - &batch, - grove_version, - ) - } else { - self.insert_without_transaction( - subtree_path, - key, - element, - options.unwrap_or_default(), - &batch, - grove_version, - ) - }; - - collect_costs.flat_map_ok(|_| { - self.db - .commit_multi_context_batch(batch, transaction) - .map_err(Into::into) - }) - } - - fn insert_on_transaction<'db, 'b, B: AsRef<[u8]>>( - &self, - path: SubtreePath<'b, B>, - key: &[u8], - element: Element, - options: InsertOptions, - transaction: &'db Transaction, - batch: &StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult<(), Error> { - check_grovedb_v0_with_cost!( - "insert_on_transaction", - grove_version - .grovedb_versions - .operations - .insert - .insert_on_transaction - ); - + let tx = TxRef::new(&self.db, transaction); let mut cost = OperationCost::default(); + let merk_cache = MerkCache::new(&self, tx.as_ref(), grove_version); - let mut merk_cache: HashMap, Merk> = - HashMap::default(); - - let merk = cost_return_on_error!( - &mut cost, - self.add_element_on_transaction( - path.clone(), - key, - element, - options, - transaction, - batch, - grove_version - ) - ); - merk_cache.insert(path.clone(), merk); cost_return_on_error!( &mut cost, - self.propagate_changes_with_transaction( - merk_cache, - path, - transaction, - batch, - grove_version - ) - ); - - Ok(()).wrap_with_cost(cost) - } - - fn insert_without_transaction<'b, B: AsRef<[u8]>>( - &self, - path: SubtreePath<'b, B>, - key: &[u8], - element: Element, - options: InsertOptions, - batch: &StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult<(), Error> { - check_grovedb_v0_with_cost!( - "insert_without_transaction", - grove_version - .grovedb_versions - .operations - .insert - .insert_without_transaction - ); - - let mut cost = OperationCost::default(); - - let mut merk_cache: HashMap, Merk> = - HashMap::default(); - - let merk = cost_return_on_error!( - &mut cost, - self.add_element_without_transaction( - &path.to_vec(), + self.add_element_on_transaction( + path.into(), key, element, - options, - batch, + options.unwrap_or_default(), + &merk_cache, grove_version ) ); - merk_cache.insert(path.clone(), merk); - - cost_return_on_error!( - &mut cost, - self.propagate_changes_without_transaction(merk_cache, path, batch, grove_version) - ); - Ok(()).wrap_with_cost(cost) + let batch = cost_return_on_error!(&mut cost, merk_cache.into_batch()); + self.db + .commit_multi_context_batch(*batch, Some(tx.as_ref())) + .map_err(Into::into) + .map_ok(|_| tx.commit_local()) + .flatten() + .add_cost(cost) } /// Add subtree to another subtree. @@ -214,16 +99,15 @@ impl GroveDb { /// first make sure other merk exist /// if it exists, then create merk to be inserted, and get root hash /// we only care about root hash of merk to be inserted - fn add_element_on_transaction<'db, B: AsRef<[u8]>>( + fn add_element_on_transaction<'db, 'b, 'c, B: AsRef<[u8]>>( &'db self, - path: SubtreePath, + path: SubtreePath<'b, B>, key: &[u8], element: Element, options: InsertOptions, - transaction: &'db Transaction, - batch: &'db StorageBatch, + merk_cache: &'c MerkCache<'db, 'b, B>, grove_version: &GroveVersion, - ) -> CostResult>, Error> { + ) -> CostResult, Error> { check_grovedb_v0_with_cost!( "add_element_on_transaction", grove_version @@ -235,27 +119,20 @@ impl GroveDb { let mut cost = OperationCost::default(); - let mut subtree_to_insert_into = cost_return_on_error!( - &mut cost, - self.open_transactional_merk_at_path( - path.clone(), - transaction, - Some(batch), - grove_version - ) - ); - // if we don't allow a tree override then we should check + let mut subtree_to_insert_into = + cost_return_on_error!(&mut cost, merk_cache.get_merk(path.derive_owned())); + // if we don't allow a tree override then we should check if options.checks_for_override() { let maybe_element_bytes = cost_return_on_error!( &mut cost, subtree_to_insert_into - .get( + .for_merk(|m| m.get( key, true, Some(&Element::value_defined_cost_for_serialized_value), grove_version, - ) + )) .map_err(|e| Error::CorruptedData(e.to_string())) ); if let Some(element_bytes) = maybe_element_bytes { @@ -267,7 +144,7 @@ impl GroveDb { } if options.validate_insertion_does_not_override_tree { let element = cost_return_on_error_no_add!( - &cost, + cost, Element::deserialize(element_bytes.as_slice(), grove_version).map_err( |_| { Error::CorruptedData(String::from("unable to deserialize element")) @@ -286,170 +163,38 @@ impl GroveDb { match element { Element::Reference(ref reference_path, ..) => { - let path = path.to_vec(); // TODO: need for support for references in path library - let reference_path = cost_return_on_error!( - &mut cost, - path_from_reference_path_type(reference_path.clone(), &path, Some(key)) - .wrap_with_cost(OperationCost::default()) - ); - - let referenced_item = cost_return_on_error!( - &mut cost, - self.follow_reference( - reference_path.as_slice().into(), - false, - Some(transaction), - grove_version - ) - ); - - let referenced_element_value_hash = - cost_return_on_error!(&mut cost, referenced_item.value_hash(grove_version)); - - cost_return_on_error!( - &mut cost, - element.insert_reference( - &mut subtree_to_insert_into, - key, - referenced_element_value_hash, - Some(options.as_merk_options()), - grove_version, - ) - ); - } - Element::Tree(ref value, _) | Element::SumTree(ref value, ..) => { - if value.is_some() { - return Err(Error::InvalidCodeExecution( - "a tree should be empty at the moment of insertion when not using batches", - )) - .wrap_with_cost(cost); - } else { - cost_return_on_error!( - &mut cost, - element.insert_subtree( - &mut subtree_to_insert_into, - key, - NULL_HASH, - Some(options.as_merk_options()), - grove_version - ) - ); - } - } - _ => { - cost_return_on_error!( + let resolved_reference = cost_return_on_error!( &mut cost, - element.insert( - &mut subtree_to_insert_into, + util::follow_reference( + merk_cache, + path.derive_owned(), key, - Some(options.as_merk_options()), - grove_version + reference_path.clone() ) ); - } - } - - Ok(subtree_to_insert_into).wrap_with_cost(cost) - } - /// Add an empty tree or item to a parent tree. - /// We want to add a new empty merk to another merk at a key - /// first make sure other merk exist - /// if it exists, then create merk to be inserted, and get root hash - /// we only care about root hash of merk to be inserted - fn add_element_without_transaction<'db, B: AsRef<[u8]>>( - &'db self, - path: &[B], - key: &[u8], - element: Element, - options: InsertOptions, - batch: &'db StorageBatch, - grove_version: &GroveVersion, - ) -> CostResult, Error> { - check_grovedb_v0_with_cost!( - "add_element_without_transaction", - grove_version - .grovedb_versions - .operations - .insert - .add_element_without_transaction - ); - - let mut cost = OperationCost::default(); - let mut subtree_to_insert_into = cost_return_on_error!( - &mut cost, - self.open_non_transactional_merk_at_path(path.into(), Some(batch), grove_version) - ); - - if options.checks_for_override() { - let maybe_element_bytes = cost_return_on_error!( - &mut cost, - subtree_to_insert_into - .get( - key, - true, - Some(&Element::value_defined_cost_for_serialized_value), - grove_version - ) - .map_err(|e| Error::CorruptedData(e.to_string())) - ); - if let Some(element_bytes) = maybe_element_bytes { - if options.validate_insertion_does_not_override { - return Err(Error::OverrideNotAllowed( - "insertion not allowed to override", + if matches!( + resolved_reference.target_element, + Element::Tree(_, _) | Element::SumTree(_, _, _) + ) { + return Err(Error::NotSupported( + "References cannot point to subtrees".to_owned(), )) .wrap_with_cost(cost); } - if options.validate_insertion_does_not_override_tree { - let element = cost_return_on_error_no_add!( - &cost, - Element::deserialize(element_bytes.as_slice(), grove_version).map_err( - |_| { - Error::CorruptedData(String::from("unable to deserialize element")) - } - ) - ); - if element.is_any_tree() { - return Err(Error::OverrideNotAllowed( - "insertion not allowed to override tree", - )) - .wrap_with_cost(cost); - } - } - } - } - - match element { - Element::Reference(ref reference_path, ..) => { - let reference_path = cost_return_on_error!( - &mut cost, - path_from_reference_path_type(reference_path.clone(), path, Some(key)) - .wrap_with_cost(OperationCost::default()) - ); - let referenced_item = cost_return_on_error!( - &mut cost, - self.follow_reference( - reference_path.as_slice().into(), - false, - None, - grove_version - ) - ); - - let referenced_element_value_hash = - cost_return_on_error!(&mut cost, referenced_item.value_hash(grove_version)); cost_return_on_error!( &mut cost, - element.insert_reference( - &mut subtree_to_insert_into, + subtree_to_insert_into.for_merk(|m| element.insert_reference( + m, key, - referenced_element_value_hash, + resolved_reference.target_node_value_hash, Some(options.as_merk_options()), - grove_version - ) + grove_version, + )) ); } + Element::Tree(ref value, _) | Element::SumTree(ref value, ..) => { if value.is_some() { return Err(Error::InvalidCodeExecution( @@ -459,25 +204,25 @@ impl GroveDb { } else { cost_return_on_error!( &mut cost, - element.insert_subtree( - &mut subtree_to_insert_into, + subtree_to_insert_into.for_merk(|m| element.insert_subtree( + m, key, NULL_HASH, Some(options.as_merk_options()), grove_version - ) + )) ); } } _ => { cost_return_on_error!( &mut cost, - element.insert( - &mut subtree_to_insert_into, + subtree_to_insert_into.for_merk(|m| element.insert( + m, key, Some(options.as_merk_options()), grove_version - ) + )) ); } } @@ -485,9 +230,6 @@ impl GroveDb { Ok(subtree_to_insert_into).wrap_with_cost(cost) } - /// Insert if not exists - /// Insert if not exists - /// /// Inserts an element at the specified path and key if it does not already /// exist. /// @@ -640,7 +382,6 @@ impl GroveDb { } } -#[cfg(feature = "full")] #[cfg(test)] mod tests { use grovedb_costs::{ diff --git a/grovedb/src/operations/is_empty_tree.rs b/grovedb/src/operations/is_empty_tree.rs index 07c349991..fe2a52955 100644 --- a/grovedb/src/operations/is_empty_tree.rs +++ b/grovedb/src/operations/is_empty_tree.rs @@ -1,16 +1,11 @@ //! Check if empty tree operations -#[cfg(feature = "full")] use grovedb_costs::{cost_return_on_error, CostResult, CostsExt, OperationCost}; use grovedb_path::SubtreePath; -#[cfg(feature = "full")] -use grovedb_version::error::GroveVersionError; use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; -#[cfg(feature = "full")] -use crate::{util::merk_optional_tx, Element, Error, GroveDb, TransactionArg}; +use crate::{util::TxRef, Error, GroveDb, TransactionArg}; -#[cfg(feature = "full")] impl GroveDb { /// Check if it's an empty tree pub fn is_empty_tree<'b, B, P>( @@ -30,19 +25,22 @@ impl GroveDb { let mut cost = OperationCost::default(); let path: SubtreePath = path.into(); + let tx = TxRef::new(&self.db, transaction); + cost_return_on_error!( &mut cost, - self.check_subtree_exists_path_not_found(path.clone(), transaction, grove_version) + self.check_subtree_exists_path_not_found( + path.clone(), + Some(tx.as_ref()), + grove_version + ) ); - merk_optional_tx!( + + let subtree = cost_return_on_error!( &mut cost, - self.db, - path, - None, - transaction, - subtree, - grove_version, - { Ok(subtree.is_empty_tree().unwrap_add_cost(&mut cost)).wrap_with_cost(cost) } - ) + self.open_transactional_merk_at_path(path, tx.as_ref(), None, grove_version) + ); + + subtree.is_empty_tree().add_cost(cost).map(Ok) } } diff --git a/grovedb/src/operations/proof/generate.rs b/grovedb/src/operations/proof/generate.rs index 6e814f67f..b914bc1a6 100644 --- a/grovedb/src/operations/proof/generate.rs +++ b/grovedb/src/operations/proof/generate.rs @@ -12,9 +12,7 @@ use grovedb_merk::{ Merk, ProofWithoutEncodingResult, }; use grovedb_storage::StorageContext; -use grovedb_version::{ - check_grovedb_v0_with_cost, error::GroveVersionError, version::GroveVersion, -}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; #[cfg(feature = "proof_debug")] use crate::query_result_type::QueryResultType; @@ -23,7 +21,7 @@ use crate::{ util::hex_to_ascii, GroveDBProof, GroveDBProofV0, LayerProof, ProveOptions, }, reference_path::path_from_reference_path_type, - Element, Error, GroveDb, PathQuery, + Element, Error, GroveDb, PathQuery, Transaction, }; impl GroveDb { @@ -89,7 +87,7 @@ impl GroveDb { .with_big_endian() .with_no_limit(); let encoded_proof = cost_return_on_error_no_add!( - &cost, + cost, bincode::encode_to_vec(proof, config) .map_err(|e| Error::CorruptedData(format!("unable to encode proof {}", e))) ); @@ -121,6 +119,8 @@ impl GroveDb { .wrap_with_cost(cost); } + let tx = self.start_transaction(); + #[cfg(feature = "proof_debug")] { // we want to query raw because we want the references to not be resolved at @@ -134,7 +134,7 @@ impl GroveDb { prove_options.decrease_limit_on_empty_sub_query_result, false, QueryResultType::QueryPathKeyElementTrioResultType, - None, + Some(&tx), grove_version, ) ) @@ -150,7 +150,7 @@ impl GroveDb { prove_options.decrease_limit_on_empty_sub_query_result, false, QueryResultType::QueryPathKeyElementTrioResultType, - None, + Some(&tx), grove_version, ) ) @@ -169,6 +169,7 @@ impl GroveDb { path_query, &mut limit, &prove_options, + &tx, grove_version ) ); @@ -189,12 +190,13 @@ impl GroveDb { path_query: &PathQuery, overall_limit: &mut Option, prove_options: &ProveOptions, + tx: &Transaction, grove_version: &GroveVersion, ) -> CostResult { let mut cost = OperationCost::default(); let query = cost_return_on_error_no_add!( - &cost, + cost, path_query .query_items_at_path(path.as_slice(), grove_version) .and_then(|query_items| { @@ -211,7 +213,7 @@ impl GroveDb { let subtree = cost_return_on_error!( &mut cost, - self.open_non_transactional_merk_at_path(path.as_slice().into(), None, grove_version) + self.open_transactional_merk_at_path(path.as_slice().into(), &tx, None, grove_version) ); let limit = if path.len() < path_query.path.len() { @@ -279,7 +281,7 @@ impl GroveDb { self.follow_reference( absolute_path.as_slice().into(), true, - None, + tx, grove_version ) ); @@ -340,6 +342,7 @@ impl GroveDb { path_query, overall_limit, prove_options, + tx, grove_version, ) ); diff --git a/grovedb/src/operations/proof/verify.rs b/grovedb/src/operations/proof/verify.rs index 1ac09c8bd..c6a34c1f4 100644 --- a/grovedb/src/operations/proof/verify.rs +++ b/grovedb/src/operations/proof/verify.rs @@ -9,8 +9,7 @@ use grovedb_merk::{ CryptoHash, }; use grovedb_version::{ - check_grovedb_v0, error::GroveVersionError, version::GroveVersion, TryFromVersioned, - TryIntoVersioned, + check_grovedb_v0, version::GroveVersion, TryFromVersioned, TryIntoVersioned, }; #[cfg(feature = "proof_debug")] diff --git a/grovedb/src/query/mod.rs b/grovedb/src/query/mod.rs index 07930c4ed..f3bcf42c3 100644 --- a/grovedb/src/query/mod.rs +++ b/grovedb/src/query/mod.rs @@ -12,7 +12,7 @@ use grovedb_merk::proofs::query::query_item::QueryItem; use grovedb_merk::proofs::query::{Key, SubqueryBranch}; #[cfg(any(feature = "full", feature = "verify"))] use grovedb_merk::proofs::Query; -use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; +use grovedb_version::{check_grovedb_v0, version::GroveVersion}; use indexmap::IndexMap; use crate::operations::proof::util::hex_to_ascii; diff --git a/grovedb/src/reference_path.rs b/grovedb/src/reference_path.rs index fcfeee6ed..a5e54f956 100644 --- a/grovedb/src/reference_path.rs +++ b/grovedb/src/reference_path.rs @@ -2,8 +2,10 @@ #[cfg(any(feature = "full", feature = "verify"))] use std::fmt; +use std::iter; use bincode::{Decode, Encode}; +use grovedb_path::{SubtreePath, SubtreePathBuilder}; #[cfg(feature = "full")] use grovedb_visualize::visualize_to_vec; #[cfg(feature = "full")] @@ -59,10 +61,89 @@ pub enum ReferencePathType { SiblingReference(Vec), } +impl ReferencePathType { + /// Get an inverted reference + pub(crate) fn invert>(&self, path: SubtreePath, key: &[u8]) -> Option { + Some(match self { + // Absolute path shall point to a fully qualified path of the reference's origin + ReferencePathType::AbsolutePathReference(_) => { + let mut qualified_path = path.to_vec(); + qualified_path.push(key.to_vec()); + ReferencePathType::AbsolutePathReference(qualified_path) + } + // Since both reference origin and path share N first segments, the backward reference + // can do the same, key we shall persist for a qualified path as the output + ReferencePathType::UpstreamRootHeightReference(n, _) => { + let relative_path: Vec<_> = path + .to_vec() + .into_iter() + .skip(*n as usize) + .chain(iter::once(key.to_vec())) + .collect(); + ReferencePathType::UpstreamRootHeightReference(*n, relative_path) + } + // Since it uses some parent information it get's complicated, so falling back to the + // preivous type of reference + ReferencePathType::UpstreamRootHeightWithParentPathAdditionReference(n, _) => { + let relative_path: Vec<_> = path + .to_vec() + .into_iter() + .skip(*n as usize) + .chain(iter::once(key.to_vec())) + .collect(); + ReferencePathType::UpstreamRootHeightReference(*n, relative_path) + } + // Discarding N latest segments is relative to the previously appended path, so it would + // be easier to discard appended paths both ways and have a shared prefix. + ReferencePathType::UpstreamFromElementHeightReference(n, append_path) => { + let mut relative_path: Vec> = path + .into_reverse_iter() + .take(*n as usize) + .map(|x| x.to_vec()) + .collect(); + relative_path.reverse(); + relative_path.push(key.to_vec()); + ReferencePathType::UpstreamFromElementHeightReference( + append_path.len() as u8 - 1, + relative_path, + ) + } + // Cousin is relative to cousin, key will remain the same + ReferencePathType::CousinReference(_) => ReferencePathType::CousinReference( + path.into_reverse_iter().next().map(|x| x.to_vec())?, + ), + // Here since any number of segments could've been added we need to resort to a more + // specific option + ReferencePathType::RemovedCousinReference(append_path) => { + let mut relative_path = + vec![path.into_reverse_iter().next().map(|x| x.to_vec())?]; + relative_path.push(key.to_vec()); + ReferencePathType::UpstreamFromElementHeightReference( + append_path.len() as u8, + relative_path, + ) + } + // The closest way back would be just to use the key + ReferencePathType::SiblingReference(_) => { + ReferencePathType::SiblingReference(key.to_vec()) + } + }) + } +} + // Helper function to display paths fn display_path(path: &[Vec]) -> String { path.iter() - .map(hex::encode) + .map(|bytes| { + let mut hx = hex::encode(bytes); + if let Ok(s) = String::from_utf8(bytes.clone()) { + hx.push_str("("); + hx.push_str(&s); + hx.push_str(")"); + } + + hx + }) .collect::>() .join("/") } @@ -132,6 +213,132 @@ impl ReferencePathType { ) -> Result>, Error> { path_from_reference_path_type(self, current_path, current_key) } + + /// TODO: deprecate the rest + pub fn absolute_qualified_path<'b, B: AsRef<[u8]>>( + self, + mut current_path: SubtreePathBuilder<'b, B>, + current_key: &[u8], + ) -> Result, Error> { + match self { + ReferencePathType::AbsolutePathReference(path) => { + Ok(SubtreePathBuilder::owned_from_iter(path)) + } + + ReferencePathType::UpstreamRootHeightReference(no_of_elements_to_keep, append_path) => { + let len = current_path.len(); + if no_of_elements_to_keep as usize > len { + return Err(Error::InvalidInput( + "reference stored path cannot satisfy reference constraints", + )); + } + let n_to_remove = len - no_of_elements_to_keep as usize; + + let referenced_path = (0..n_to_remove).fold(current_path, |p, _| { + p.derive_parent_owned() + .expect("lenghts were checked above") + .0 + }); + let referenced_path = append_path.into_iter().fold(referenced_path, |mut p, s| { + p.push_segment(&s); + p + }); + + Ok(referenced_path) + } + + ReferencePathType::UpstreamRootHeightWithParentPathAdditionReference( + no_of_elements_to_keep, + append_path, + ) => { + let len = current_path.len(); + if no_of_elements_to_keep as usize > len || len < 1 { + return Err(Error::InvalidInput( + "reference stored path cannot satisfy reference constraints", + )); + } + + let parent_key = current_path + .reverse_iter() + .next() + .expect("lengths were checked above") + .to_vec(); + + let n_to_remove = len - no_of_elements_to_keep as usize; + + let referenced_path = (0..n_to_remove).fold(current_path, |p, _| { + p.derive_parent_owned() + .expect("lenghts were checked above") + .0 + }); + let mut referenced_path = + append_path.into_iter().fold(referenced_path, |mut p, s| { + p.push_segment(&s); + p + }); + referenced_path.push_segment(&parent_key); + + Ok(referenced_path) + } + + // Discard the last n elements from current path, append new path to subpath + ReferencePathType::UpstreamFromElementHeightReference( + no_of_elements_to_discard_from_end, + append_path, + ) => { + let mut referenced_path = current_path; + for _ in 0..no_of_elements_to_discard_from_end { + if let Some((path, _)) = referenced_path.derive_parent_owned() { + referenced_path = path; + } else { + return Err(Error::InvalidInput( + "reference stored path cannot satisfy reference constraints", + )); + } + } + + let referenced_path = append_path.into_iter().fold(referenced_path, |mut p, s| { + p.push_segment(&s); + p + }); + + Ok(referenced_path) + } + + ReferencePathType::CousinReference(cousin_key) => { + let Some((mut referred_path, _)) = current_path.derive_parent_owned() else { + return Err(Error::InvalidInput( + "reference stored path cannot satisfy reference constraints", + )); + }; + + referred_path.push_segment(&cousin_key); + referred_path.push_segment(current_key); + + Ok(referred_path) + } + + ReferencePathType::RemovedCousinReference(cousin_path) => { + let Some((mut referred_path, _)) = current_path.derive_parent_owned() else { + return Err(Error::InvalidInput( + "reference stored path cannot satisfy reference constraints", + )); + }; + + cousin_path + .into_iter() + .for_each(|s| referred_path.push_segment(&s)); + referred_path.push_segment(current_key); + + Ok(referred_path) + } + + ReferencePathType::SiblingReference(sibling_key) => { + current_path.push_segment(&sibling_key); + Ok(current_path) + } + } + } } #[cfg(any(feature = "full", feature = "visualize"))] @@ -170,7 +377,6 @@ pub fn path_from_reference_path_type>( current_key: Option<&[u8]>, ) -> Result>, Error> { match reference_path_type { - // No computation required, we already know the absolute path ReferencePathType::AbsolutePathReference(path) => Ok(path), // Take the first n elements from current path, append new path to subpath @@ -324,6 +530,7 @@ impl ReferencePathType { #[cfg(test)] mod tests { use grovedb_merk::proofs::Query; + use grovedb_path::{SubtreePath, SubtreePathBuilder}; use grovedb_version::version::GroveVersion; use crate::{ @@ -345,6 +552,20 @@ mod tests { ); } + #[test] + fn test_upstream_root_height_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]); + // selects the first 2 elements from the stored path and appends the new path. + let ref1 = + ReferencePathType::UpstreamRootHeightReference(2, vec![b"c".to_vec(), b"d".to_vec()]); + let final_path = ref1.absolute_qualified_path(stored_path, b"").unwrap(); + assert_eq!( + final_path.to_vec(), + vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), b"d".to_vec()] + ); + } + #[test] fn test_upstream_root_height_with_parent_addition_reference() { let stored_path = vec![b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]; @@ -366,6 +587,28 @@ mod tests { ); } + #[test] + fn test_upstream_root_height_with_parent_addition_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]); + // selects the first 2 elements from the stored path and appends the new path. + let ref1 = ReferencePathType::UpstreamRootHeightWithParentPathAdditionReference( + 2, + vec![b"c".to_vec(), b"d".to_vec()], + ); + let final_path = ref1.absolute_qualified_path(stored_path, b"").unwrap(); + assert_eq!( + final_path.to_vec(), + vec![ + b"a".to_vec(), + b"b".to_vec(), + b"c".to_vec(), + b"d".to_vec(), + b"m".to_vec() + ] + ); + } + #[test] fn test_upstream_from_element_height_reference() { let stored_path = vec![b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]; @@ -381,6 +624,22 @@ mod tests { ); } + #[test] + fn test_upstream_from_element_height_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]); + // discards the last element from the stored_path + let ref1 = ReferencePathType::UpstreamFromElementHeightReference( + 1, + vec![b"c".to_vec(), b"d".to_vec()], + ); + let final_path = ref1.absolute_qualified_path(stored_path, b"").unwrap(); + assert_eq!( + final_path.to_vec(), + vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), b"d".to_vec()] + ); + } + #[test] fn test_cousin_reference_no_key() { let stored_path = vec![b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]; @@ -403,6 +662,20 @@ mod tests { ); } + #[test] + fn test_cousin_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref()]); + let key = b"m".as_ref(); + // Replaces the immediate parent (in this case b) with the given key (c) + let ref1 = ReferencePathType::CousinReference(b"c".to_vec()); + let final_path = ref1.absolute_qualified_path(stored_path, key).unwrap(); + assert_eq!( + final_path.to_vec(), + vec![b"a".to_vec(), b"c".to_vec(), b"m".to_vec()] + ); + } + #[test] fn test_removed_cousin_reference_no_key() { let stored_path = vec![b"a".as_ref(), b"b".as_ref(), b"m".as_ref()]; @@ -425,6 +698,20 @@ mod tests { ); } + #[test] + fn test_removed_cousin_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref()]); + let key = b"m".as_ref(); + // Replaces the immediate parent (in this case b) with the given key (c) + let ref1 = ReferencePathType::RemovedCousinReference(vec![b"c".to_vec(), b"d".to_vec()]); + let final_path = ref1.absolute_qualified_path(stored_path, key).unwrap(); + assert_eq!( + final_path.to_vec(), + vec![b"a".to_vec(), b"c".to_vec(), b"d".to_vec(), b"m".to_vec()] + ); + } + #[test] fn test_sibling_reference() { let stored_path = vec![b"a".as_ref(), b"b".as_ref()]; @@ -437,6 +724,19 @@ mod tests { ); } + #[test] + fn test_sibling_reference_path_lib() { + let stored_path: SubtreePathBuilder<&[u8]> = + SubtreePathBuilder::owned_from_iter([b"a".as_ref(), b"b".as_ref()]); + let key = b"m".as_ref(); + let ref1 = ReferencePathType::SiblingReference(b"c".to_vec()); + let final_path = ref1.absolute_qualified_path(stored_path, key).unwrap(); + assert_eq!( + final_path.to_vec(), + vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()] + ); + } + #[test] fn test_query_many_with_different_reference_types() { let grove_version = GroveVersion::latest(); @@ -515,4 +815,251 @@ mod tests { assert_eq!(hash, db.root_hash(None, grove_version).unwrap().unwrap()); assert_eq!(result.len(), 5); } + + #[test] + fn inverted_absolute_path() { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + + let reference = + ReferencePathType::AbsolutePathReference(vec![b"m".to_vec(), b"n".to_vec()]); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + + assert_eq!( + reference, + inverse + .invert(pointed_to_path.into(), pointed_to_key) + .unwrap() + ); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path + ); + } + + #[test] + fn inverted_upstream_root_height() { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + + let reference = + ReferencePathType::UpstreamRootHeightReference(2, vec![b"m".to_vec(), b"n".to_vec()]); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), None) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + + assert_eq!( + reference, + inverse + .invert(pointed_to_path.into(), pointed_to_key) + .unwrap() + ); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path.to_vec(), + ); + } + + #[test] + fn inverted_upstream_root_height_with_parent_path_addition() { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + let reference = ReferencePathType::UpstreamRootHeightWithParentPathAdditionReference( + 2, + vec![b"m".to_vec(), b"n".to_vec()], + ); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path.to_vec(), + ); + } + + #[test] + fn inverted_upstream_from_element_height() { + { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + let reference = ReferencePathType::UpstreamFromElementHeightReference( + 1, + vec![b"m".to_vec(), b"n".to_vec()], + ); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + + assert_eq!( + reference, + inverse + .invert(pointed_to_path.into(), pointed_to_key) + .unwrap() + ); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path.to_vec(), + ); + } + + { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + let reference = ReferencePathType::UpstreamFromElementHeightReference( + 3, + vec![b"m".to_vec(), b"n".to_vec()], + ); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + + assert_eq!( + reference, + inverse + .invert(pointed_to_path.into(), pointed_to_key) + .unwrap() + ); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path.to_vec(), + ); + } + } + + #[test] + fn inverted_cousin_reference() { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + let reference = + ReferencePathType::RemovedCousinReference(vec![b"m".to_vec(), b"n".to_vec()]); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path + ); + } + + #[test] + fn inverted_sibling_reference() { + let current_path: SubtreePath<_> = (&[b"a", b"b", b"c", b"d"]).into(); + let current_key = b"e"; + let current_qualified_path = { + let mut p = current_path.to_vec(); + p.push(current_key.to_vec()); + p + }; + let reference = ReferencePathType::SiblingReference(b"yeet".to_vec()); + + let pointed_to_qualified_path = reference + .clone() + .absolute_path(¤t_path.to_vec(), Some(current_key)) + .unwrap(); + let (pointed_to_key, pointed_to_path) = pointed_to_qualified_path.split_last().unwrap(); + + let inverse = reference.invert(current_path.clone(), current_key).unwrap(); + + assert_ne!(reference, inverse); + assert_eq!( + reference, + inverse + .invert(pointed_to_path.into(), pointed_to_key) + .unwrap() + ); + assert_eq!( + inverse + .absolute_path(&pointed_to_path, Some(pointed_to_key)) + .unwrap(), + current_qualified_path + ); + } } diff --git a/grovedb/src/replication.rs b/grovedb/src/replication.rs index 876fe62c1..8e33df50f 100644 --- a/grovedb/src/replication.rs +++ b/grovedb/src/replication.rs @@ -16,7 +16,7 @@ use grovedb_storage::rocksdb_storage::RocksDbStorage; use grovedb_storage::rocksdb_storage::storage_context::context_immediate::PrefixedRocksDbImmediateStorageContext; use grovedb_version::{check_grovedb_v0, error::GroveVersionError, version::GroveVersion}; -use crate::{replication, Error, GroveDb, Transaction, TransactionArg}; +use crate::{replication, util::TxRef, Error, GroveDb, Transaction, TransactionArg}; pub(crate) type SubtreePrefix = [u8; blake3::OUT_LEN]; @@ -169,7 +169,7 @@ impl GroveDb { // of root (as it is now) pub fn get_subtrees_metadata( &self, - tx: TransactionArg, + transaction: TransactionArg, grove_version: &GroveVersion, ) -> Result { check_grovedb_v0!( @@ -181,8 +181,10 @@ impl GroveDb { ); let mut subtrees_metadata = SubtreesMetadata::new(); + let tx = TxRef::new(&self.db, transaction); + let subtrees_root = self - .find_subtrees(&SubtreePath::empty(), tx, grove_version) + .find_subtrees(&SubtreePath::empty(), Some(tx.as_ref()), grove_version) .value?; for subtree in subtrees_root.into_iter() { let subtree_path: Vec<&[u8]> = subtree.iter().map(|vec| vec.as_slice()).collect(); @@ -192,48 +194,31 @@ impl GroveDb { let current_path = SubtreePath::from(path); match (current_path.derive_parent(), subtree.last()) { - (Some((parent_path, _)), Some(parent_key)) => match tx { - None => { - let parent_merk = self - .open_non_transactional_merk_at_path(parent_path, None, grove_version) - .value?; - if let Ok(Some((elem_value, elem_value_hash))) = parent_merk - .get_value_and_value_hash( - parent_key, - true, - None::<&fn(&[u8], &GroveVersion) -> Option>, - grove_version, - ) - .value - { - let actual_value_hash = value_hash(&elem_value).unwrap(); - subtrees_metadata.data.insert( - prefix, - (current_path.to_vec(), actual_value_hash, elem_value_hash), - ); - } - } - Some(t) => { - let parent_merk = self - .open_transactional_merk_at_path(parent_path, t, None, grove_version) - .value?; - if let Ok(Some((elem_value, elem_value_hash))) = parent_merk - .get_value_and_value_hash( - parent_key, - true, - None::<&fn(&[u8], &GroveVersion) -> Option>, - grove_version, - ) - .value - { - let actual_value_hash = value_hash(&elem_value).unwrap(); - subtrees_metadata.data.insert( - prefix, - (current_path.to_vec(), actual_value_hash, elem_value_hash), - ); - } + (Some((parent_path, _)), Some(parent_key)) => { + let parent_merk = self + .open_transactional_merk_at_path( + parent_path, + tx.as_ref(), + None, + grove_version, + ) + .value?; + if let Ok(Some((elem_value, elem_value_hash))) = parent_merk + .get_value_and_value_hash( + parent_key, + true, + None::<&fn(&[u8], &GroveVersion) -> Option>, + grove_version, + ) + .value + { + let actual_value_hash = value_hash(&elem_value).unwrap(); + subtrees_metadata.data.insert( + prefix, + (current_path.to_vec(), actual_value_hash, elem_value_hash), + ); } - }, + } _ => { subtrees_metadata.data.insert( prefix, @@ -262,7 +247,7 @@ impl GroveDb { pub fn fetch_chunk( &self, global_chunk_id: &[u8], - tx: TransactionArg, + transaction: TransactionArg, version: u16, grove_version: &GroveVersion, ) -> Result, Error> { @@ -277,11 +262,13 @@ impl GroveDb { )); } - let root_app_hash = self.root_hash(tx, grove_version).value?; + let tx = TxRef::new(&self.db, transaction); + + let root_app_hash = self.root_hash(Some(tx.as_ref()), grove_version).value?; let (chunk_prefix, chunk_id) = replication::util_split_global_chunk_id(global_chunk_id, &root_app_hash)?; - let subtrees_metadata = self.get_subtrees_metadata(tx, grove_version)?; + let subtrees_metadata = self.get_subtrees_metadata(Some(tx.as_ref()), grove_version)?; match subtrees_metadata.data.get(&chunk_prefix) { Some(path_data) => { @@ -289,67 +276,33 @@ impl GroveDb { let subtree_path: Vec<&[u8]> = subtree.iter().map(|vec| vec.as_slice()).collect(); let path: &[&[u8]] = &subtree_path; - match tx { - None => { - let merk = self - .open_non_transactional_merk_at_path(path.into(), None, grove_version) - .value?; + let merk = self + .open_transactional_merk_at_path(path.into(), tx.as_ref(), None, grove_version) + .value?; - if merk.is_empty_tree().unwrap() { - return Ok(vec![]); - } - - let chunk_producer_res = ChunkProducer::new(&merk); - match chunk_producer_res { - Ok(mut chunk_producer) => { - let chunk_res = chunk_producer.chunk(&chunk_id, grove_version); - match chunk_res { - Ok((chunk, _)) => match util_encode_vec_ops(chunk) { - Ok(op_bytes) => Ok(op_bytes), - Err(_) => Err(Error::CorruptedData( - "Unable to create to load chunk".to_string(), - )), - }, - Err(_) => Err(Error::CorruptedData( - "Unable to create to load chunk".to_string(), - )), - } - } - Err(_) => Err(Error::CorruptedData( - "Unable to create Chunk producer".to_string(), - )), - } - } - Some(t) => { - let merk = self - .open_transactional_merk_at_path(path.into(), t, None, grove_version) - .value?; - - if merk.is_empty_tree().unwrap() { - return Ok(vec![]); - } + if merk.is_empty_tree().unwrap() { + return Ok(vec![]); + } - let chunk_producer_res = ChunkProducer::new(&merk); - match chunk_producer_res { - Ok(mut chunk_producer) => { - let chunk_res = chunk_producer.chunk(&chunk_id, grove_version); - match chunk_res { - Ok((chunk, _)) => match util_encode_vec_ops(chunk) { - Ok(op_bytes) => Ok(op_bytes), - Err(_) => Err(Error::CorruptedData( - "Unable to create to load chunk".to_string(), - )), - }, - Err(_) => Err(Error::CorruptedData( - "Unable to create to load chunk".to_string(), - )), - } - } + let chunk_producer_res = ChunkProducer::new(&merk); + match chunk_producer_res { + Ok(mut chunk_producer) => { + let chunk_res = chunk_producer.chunk(&chunk_id, grove_version); + match chunk_res { + Ok((chunk, _)) => match util_encode_vec_ops(chunk) { + Ok(op_bytes) => Ok(op_bytes), + Err(_) => Err(Error::CorruptedData( + "Unable to create to load chunk".to_string(), + )), + }, Err(_) => Err(Error::CorruptedData( - "Unable to create Chunk producer".to_string(), + "Unable to create to load chunk".to_string(), )), } } + Err(_) => Err(Error::CorruptedData( + "Unable to create Chunk producer".to_string(), + )), } } None => Err(Error::CorruptedData("Prefix not found".to_string())), diff --git a/grovedb/src/tests/mod.rs b/grovedb/src/tests/mod.rs index 412636691..126e3654a 100644 --- a/grovedb/src/tests/mod.rs +++ b/grovedb/src/tests/mod.rs @@ -110,39 +110,39 @@ pub fn make_deep_tree(grove_version: &GroveVersion) -> TempGroveDb { // root // test_leaf // innertree - // k1,v1 - // k2,v2 - // k3,v3 + // key1,value1 + // key2,value2 + // key3,value3 // innertree4 - // k4,v4 - // k5,v5 + // key4,value4 + // key5,value5 // another_test_leaf // innertree2 - // k3,v3 + // key3,value3 // innertree3 - // k4,v4 + // key4,value4 // deep_leaf // deep_node_1 // deeper_1 - // k1,v1 - // k2,v2 - // k3,v3 + // key1,value1 + // key2,value2 + // key3,value3 // deeper_2 - // k4,v4 - // k5,v5 - // k6,v6 + // key4,value4 + // key5,value5 + // key6,value6 // deep_node_2 // deeper_3 - // k7,v7 - // k8,v8 - // k9,v9 + // key7,value7 + // key8,value8 + // key9,value9 // deeper_4 - // k10,v10 - // k11,v11 + // key10,value10 + // key11,value11 // deeper_5 - // k12,v12 - // k13,v13 - // k14,v14 + // key12,value12 + // key13,value13 + // key14,value14 // Insert elements into grovedb instance let temp_db = make_test_grovedb(grove_version); @@ -1190,8 +1190,6 @@ mod tests { ) .unwrap(); - dbg!(&result); - assert!(matches!( result, Err(Error::CorruptedReferencePathKeyNotFound(_)) @@ -3118,10 +3116,13 @@ mod tests { // let mut iter = db // .elements_iterator([TEST_LEAF, b"subtree1"].as_ref(), None) // .expect("cannot create iterator"); + + let tx = db.start_transaction(); + let storage_context = db .grove_db .db - .get_storage_context([TEST_LEAF, b"subtree1"].as_ref().into(), None) + .get_transactional_storage_context([TEST_LEAF, b"subtree1"].as_ref().into(), None, &tx) .unwrap(); let mut iter = Element::iterator(storage_context.raw_iter()).unwrap(); assert_eq!( @@ -3210,7 +3211,12 @@ mod tests { fn test_root_subtree_has_root_key() { let grove_version = GroveVersion::latest(); let db = make_test_grovedb(grove_version); - let storage = db.db.get_storage_context(EMPTY_PATH, None).unwrap(); + let tx = db.start_transaction(); + + let storage = db + .db + .get_transactional_storage_context(EMPTY_PATH, None, &tx) + .unwrap(); let root_merk = Merk::open_base( storage, false, @@ -3310,10 +3316,16 @@ mod tests { // Retrieve subtree instance // Check if it returns the same instance that was inserted { + let tx = db.start_transaction(); + let subtree_storage = db .grove_db .db - .get_storage_context([TEST_LEAF, b"key1", b"key2"].as_ref().into(), None) + .get_transactional_storage_context( + [TEST_LEAF, b"key1", b"key2"].as_ref().into(), + None, + &tx, + ) .unwrap(); let subtree = Merk::open_layered_with_root_key( subtree_storage, @@ -3379,10 +3391,15 @@ mod tests { assert_eq!(result_element, Element::new_item(b"ayy".to_vec())); // Should be able to retrieve instances created before transaction + let tx = db.start_transaction(); let subtree_storage = db .grove_db .db - .get_storage_context([TEST_LEAF, b"key1", b"key2"].as_ref().into(), None) + .get_transactional_storage_context( + [TEST_LEAF, b"key1", b"key2"].as_ref().into(), + None, + &tx, + ) .unwrap(); let subtree = Merk::open_layered_with_root_key( subtree_storage, @@ -3910,7 +3927,7 @@ mod tests { assert!(elem_result.is_err()); assert!(matches!( elem_result, - Err(Error::PathParentLayerNotFound(..)) + Err(Error::InvalidParentLayerPath(..)) )); } @@ -4125,3 +4142,21 @@ mod tests { .is_empty()); } } + +#[test] +fn subtrees_cant_be_referenced() { + let db = make_deep_tree(&GroveVersion::latest()); + assert!(db + .insert( + SubtreePath::empty(), + b"test_ref", + Element::new_reference(ReferencePathType::AbsolutePathReference(vec![ + TEST_LEAF.to_vec() + ])), + None, + None, + &GroveVersion::latest(), + ) + .unwrap() + .is_err()); +} diff --git a/grovedb/src/tests/sum_tree_tests.rs b/grovedb/src/tests/sum_tree_tests.rs index b255f6535..9af44026f 100644 --- a/grovedb/src/tests/sum_tree_tests.rs +++ b/grovedb/src/tests/sum_tree_tests.rs @@ -5,7 +5,7 @@ use grovedb_merk::{ tree::kv::ValueDefinedCostType, TreeFeatureType::{BasicMerkNode, SummedMerkNode}, }; -use grovedb_storage::StorageBatch; +use grovedb_storage::{Storage, StorageBatch}; use grovedb_version::version::GroveVersion; use crate::{ @@ -264,11 +264,13 @@ fn test_homogenous_node_type_in_sum_trees_and_regular_trees() { .expect("should insert item"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); // Open merk and check all elements in it let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -352,10 +354,12 @@ fn test_homogenous_node_type_in_sum_trees_and_regular_trees() { ) .unwrap() .expect("should insert item"); + let tx = db.start_transaction(); let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -402,12 +406,14 @@ fn test_sum_tree_feature() { .expect("should insert tree"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); // Sum should be non for non sum tree // TODO: change interface to retrieve element directly let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -421,13 +427,14 @@ fn test_sum_tree_feature() { b"key2", Element::empty_sum_tree(), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert sum tree"); + let sum_tree = db - .get([TEST_LEAF].as_ref(), b"key2", None, grove_version) + .get([TEST_LEAF].as_ref(), b"key2", Some(&tx), grove_version) .unwrap() .expect("should retrieve tree"); assert_eq!(sum_tree.sum_value_or_default(), 0); @@ -438,15 +445,16 @@ fn test_sum_tree_feature() { b"item1", Element::new_sum_item(30), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert item"); // TODO: change interface to retrieve element directly let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -460,7 +468,7 @@ fn test_sum_tree_feature() { b"item2", Element::new_sum_item(-10), None, - None, + Some(&tx), grove_version, ) .unwrap() @@ -470,14 +478,15 @@ fn test_sum_tree_feature() { b"item3", Element::new_sum_item(50), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert item"); let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -491,14 +500,15 @@ fn test_sum_tree_feature() { b"item4", Element::new_item(vec![29]), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert item"); let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -512,7 +522,7 @@ fn test_sum_tree_feature() { b"item2", Element::new_sum_item(10), None, - None, + Some(&tx), grove_version, ) .unwrap() @@ -522,14 +532,15 @@ fn test_sum_tree_feature() { b"item3", Element::new_sum_item(-100), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert item"); let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -542,7 +553,7 @@ fn test_sum_tree_feature() { [TEST_LEAF, b"key2"].as_ref(), b"item4", None, - None, + Some(&tx), grove_version, ) .unwrap() @@ -553,14 +564,15 @@ fn test_sum_tree_feature() { b"item4", Element::new_sum_item(10000000), None, - None, + Some(&tx), grove_version, ) .unwrap() .expect("should insert item"); let merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -668,11 +680,13 @@ fn test_sum_tree_propagation() { assert_eq!(sum_tree.sum_value_or_default(), 35); let batch = StorageBatch::new(); + let tx = db.start_transaction(); // Assert node feature types let test_leaf_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -692,8 +706,9 @@ fn test_sum_tree_propagation() { )); let parent_sum_tree = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -715,8 +730,9 @@ fn test_sum_tree_propagation() { )); let child_sum_tree = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key", b"tree2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -800,9 +816,12 @@ fn test_sum_tree_with_batches() { .expect("should apply batch"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); + let sum_tree = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -840,14 +859,24 @@ fn test_sum_tree_with_batches() { b"c".to_vec(), Element::new_sum_item(10), )]; - db.apply_batch(ops, None, None, grove_version) + db.apply_batch(ops, None, Some(&tx), grove_version) .unwrap() .expect("should apply batch"); + db.db + .commit_multi_context_batch(batch, Some(&tx)) + .unwrap() + .unwrap(); + + db.commit_transaction(tx).unwrap().unwrap(); + let batch = StorageBatch::new(); + let tx = db.start_transaction(); + let sum_tree = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -932,9 +961,12 @@ fn test_sum_tree_with_batches() { .expect("should apply batch"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); + let sum_tree = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, Some(&batch), grove_version, ) diff --git a/grovedb/src/tests/tree_hashes_tests.rs b/grovedb/src/tests/tree_hashes_tests.rs index e86b8fd0a..2ca66b493 100644 --- a/grovedb/src/tests/tree_hashes_tests.rs +++ b/grovedb/src/tests/tree_hashes_tests.rs @@ -56,10 +56,12 @@ fn test_node_hashes_when_inserting_item() { .expect("successful subtree insert"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); let test_leaf_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -130,9 +132,12 @@ fn test_tree_hashes_when_inserting_empty_tree() { let batch = StorageBatch::new(); + let tx = db.start_transaction(); + let test_leaf_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -173,8 +178,9 @@ fn test_tree_hashes_when_inserting_empty_tree() { .expect("value hash should be some"); let underlying_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -225,10 +231,12 @@ fn test_tree_hashes_when_inserting_empty_trees_twice_under_each_other() { .expect("successful subtree insert"); let batch = StorageBatch::new(); + let tx = db.start_transaction(); let under_top_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -236,8 +244,9 @@ fn test_tree_hashes_when_inserting_empty_trees_twice_under_each_other() { .expect("should open merk"); let middle_merk_key1 = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1"].as_ref().into(), + &tx, Some(&batch), grove_version, ) @@ -258,8 +267,9 @@ fn test_tree_hashes_when_inserting_empty_trees_twice_under_each_other() { .expect("value hash should be some"); let bottom_merk = db - .open_non_transactional_merk_at_path( + .open_transactional_merk_at_path( [TEST_LEAF, b"key1", b"key2"].as_ref().into(), + &tx, Some(&batch), grove_version, ) diff --git a/grovedb/src/util.rs b/grovedb/src/util.rs index b9b624a44..70db057c0 100644 --- a/grovedb/src/util.rs +++ b/grovedb/src/util.rs @@ -1,515 +1,325 @@ -/// Macro to execute same piece of code on different storage contexts -/// (transactional or not) using path argument. -macro_rules! storage_context_optional_tx { - ($db:expr, $path:expr, $batch:expr, $transaction:ident, $storage:ident, { $($body:tt)* }) => { - { - use ::grovedb_storage::Storage; - if let Some(tx) = $transaction { - let $storage = $db - .get_transactional_storage_context($path, $batch, tx); - $($body)* - } else { - let $storage = $db - .get_storage_context($path, $batch); - $($body)* - } - } - }; +use std::collections::HashSet; + +use grovedb_costs::{ + cost_return_on_error, cost_return_on_error_no_add, CostResult, CostsExt, OperationCost, +}; +use grovedb_merk::{CryptoHash, Merk}; +use grovedb_path::{SubtreePath, SubtreePathBuilder}; +use grovedb_storage::{ + rocksdb_storage::{PrefixedRocksDbTransactionContext, RocksDbStorage}, + Storage, StorageBatch, +}; +use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; +use grovedb_visualize::DebugByteVectors; + +use crate::{ + merk_cache::{MerkCache, MerkHandle}, + operations::MAX_REFERENCE_HOPS, + reference_path::ReferencePathType, + Element, Error, Transaction, TransactionArg, +}; + +pub(crate) enum TxRef<'a, 'db: 'a> { + Owned(Transaction<'db>), + Borrowed(&'a Transaction<'db>), } -/// Macro to execute same piece of code on different storage contexts -/// (transactional or not) using path argument. -macro_rules! storage_context_with_parent_optional_tx { - ( - &mut $cost:ident, - $db:expr, - $path:expr, - $batch:expr, - $transaction:ident, - $storage:ident, - $root_key:ident, - $is_sum_tree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - { - use ::grovedb_storage::Storage; - if let Some(tx) = $transaction { - let $storage = $db - .get_transactional_storage_context($path.clone(), $batch, tx) - .unwrap_add_cost(&mut $cost); - if let Some((parent_path, parent_key)) = $path.derive_parent() { - let parent_storage = $db - .get_transactional_storage_context(parent_path, $batch, tx) - .unwrap_add_cost(&mut $cost); - let element = cost_return_on_error!( - &mut $cost, - Element::get_from_storage(&parent_storage, parent_key, $grove_version) - .map_err(|e| { - Error::PathParentLayerNotFound( - format!( - "could not get key for parent of subtree optional on tx: {}", - e - ) - ) - }) - ); - match element { - Element::Tree(root_key, _) => { - let $root_key = root_key; - let $is_sum_tree = false; - $($body)* - } - Element::SumTree(root_key, ..) => { - let $root_key = root_key; - let $is_sum_tree = true; - $($body)* - } - _ => { - return Err(Error::CorruptedData( - "parent is not a tree" - .to_owned(), - )).wrap_with_cost($cost); - } - } - } else { - return Err(Error::CorruptedData( - "path is empty".to_owned(), - )).wrap_with_cost($cost); - } - } else { - let $storage = $db - .get_storage_context($path.clone(), $batch).unwrap_add_cost(&mut $cost); - if let Some((parent_path, parent_key)) = $path.derive_parent() { - let parent_storage = $db.get_storage_context( - parent_path, $batch - ).unwrap_add_cost(&mut $cost); - let element = cost_return_on_error!( - &mut $cost, - Element::get_from_storage(&parent_storage, parent_key, $grove_version).map_err(|e| { - Error::PathParentLayerNotFound( - format!( - "could not get key for parent of subtree optional no tx: {}", - e - ) - ) - }) - ); - match element { - Element::Tree(root_key, _) => { - let $root_key = root_key; - let $is_sum_tree = false; - $($body)* - } - Element::SumTree(root_key, ..) => { - let $root_key = root_key; - let $is_sum_tree = true; - $($body)* - } - _ => { - return Err(Error::CorruptedData( - "parent is not a tree" - .to_owned(), - )).wrap_with_cost($cost); - } - } - } else { - return Err(Error::CorruptedData( - "path is empty".to_owned(), - )).wrap_with_cost($cost); - } - } +impl<'a, 'db> TxRef<'a, 'db> { + pub(crate) fn new(db: &'db RocksDbStorage, transaction_arg: TransactionArg<'db, 'a>) -> Self { + if let Some(tx) = transaction_arg { + Self::Borrowed(tx) + } else { + Self::Owned(db.start_transaction()) } - }; -} + } -/// Macro to execute same piece of code on different storage contexts -/// (transactional or not) using path argument. -macro_rules! storage_context_with_parent_optional_tx_internal_error { - ( - &mut $cost:ident, - $db:expr, - $path:expr, - $batch:expr, - $transaction:ident, - $storage:ident, - $root_key:ident, - $is_sum_tree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - { - use ::grovedb_storage::Storage; - if let Some(tx) = $transaction { - let $storage = $db - .get_transactional_storage_context($path.clone(), $batch, tx) - .unwrap_add_cost(&mut $cost); - if let Some((parent_path, parent_key)) = $path.derive_parent() { - let parent_storage = $db - .get_transactional_storage_context(parent_path, $batch, tx) - .unwrap_add_cost(&mut $cost); - let result = Element::get_from_storage( - &parent_storage, - parent_key, - $grove_version - ).map_err(|e| { - Error::PathParentLayerNotFound( - format!( - "could not get key for parent of subtree optional on tx: {}", - e - ) - ) - }).unwrap_add_cost(&mut $cost); - match result { - Ok(element) => { - match element { - Element::Tree(root_key, _) => { - let $root_key = root_key; - let $is_sum_tree = false; - $($body)* - } - Element::SumTree(root_key, ..) => { - let $root_key = root_key; - let $is_sum_tree = true; - $($body)* - } - _ => { - return Err(Error::CorruptedData( - "parent is not a tree" - .to_owned(), - )).wrap_with_cost($cost); - } - } - }, - Err(e) => Err(e), - } - } else { - return Err(Error::CorruptedData( - "path is empty".to_owned(), - )).wrap_with_cost($cost); - } - } else { - let $storage = $db - .get_storage_context($path.clone(), $batch).unwrap_add_cost(&mut $cost); - if let Some((parent_path, parent_key)) = $path.derive_parent() { - let parent_storage = $db.get_storage_context( - parent_path, - $batch - ).unwrap_add_cost(&mut $cost); - let result = Element::get_from_storage( - &parent_storage, - parent_key, - $grove_version - ).map_err(|e| { - Error::PathParentLayerNotFound( - format!( - "could not get key for parent of subtree optional no tx: {}", - e - ) - ) - }).unwrap_add_cost(&mut $cost); - match result { - Ok(element) => { - match element { - Element::Tree(root_key, _) => { - let $root_key = root_key; - let $is_sum_tree = false; - $($body)* - } - Element::SumTree(root_key, ..) => { - let $root_key = root_key; - let $is_sum_tree = true; - $($body)* - } - _ => { - return Err(Error::CorruptedData( - "parent is not a tree" - .to_owned(), - )).wrap_with_cost($cost); - } - } - }, - Err(e) => Err(e), - } - } else { - return Err(Error::CorruptedData( - "path is empty".to_owned(), - )).wrap_with_cost($cost); - } - } + /// Commit the transaction if it wasn't received from outside + pub(crate) fn commit_local(self) -> Result<(), Error> { + match self { + TxRef::Owned(tx) => tx + .commit() + .map_err(|e| grovedb_storage::Error::from(e).into()), + TxRef::Borrowed(_) => Ok(()), } - }; + } } -/// Macro to execute same piece of code on different storage contexts with -/// empty prefix. -macro_rules! meta_storage_context_optional_tx { - ($db:expr, $batch:expr, $transaction:ident, $storage:ident, { $($body:tt)* }) => { - { - use ::grovedb_storage::Storage; - if let Some(tx) = $transaction { - let $storage = $db - .get_transactional_storage_context( - ::grovedb_path::SubtreePath::empty(), - $batch, - tx - ); - $($body)* - } else { - let $storage = $db - .get_storage_context( - ::grovedb_path::SubtreePath::empty(), - $batch - ); - $($body)* - } +impl<'a, 'db> AsRef> for TxRef<'a, 'db> { + fn as_ref(&self) -> &Transaction<'db> { + match self { + TxRef::Owned(tx) => tx, + TxRef::Borrowed(tx) => tx, } - }; + } } -/// Macro to execute same piece of code on Merk with varying storage -/// contexts. -macro_rules! merk_optional_tx { - ( - &mut $cost:ident, - $db:expr, - $path:expr, - $batch:expr, - $transaction:ident, - $subtree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - if $path.is_root() { - use crate::util::storage_context_optional_tx; - storage_context_optional_tx!( - $db, - ::grovedb_path::SubtreePath::empty(), - $batch, - $transaction, - storage, - { - let $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_base( - storage.unwrap_add_cost(&mut $cost), - false, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version, - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* +pub(crate) fn open_transactional_merk_at_path<'db, 'b, B>( + db: &'db RocksDbStorage, + path: SubtreePath<'b, B>, + tx: &'db Transaction, + batch: Option<&'db StorageBatch>, + grove_version: &GroveVersion, +) -> CostResult>, Error> +where + B: AsRef<[u8]> + 'b, +{ + let mut cost = OperationCost::default(); + + let storage = db + .get_transactional_storage_context(path.clone(), batch, tx) + .unwrap_add_cost(&mut cost); + if let Some((parent_path, parent_key)) = path.derive_parent() { + let parent_storage = db + .get_transactional_storage_context(parent_path.clone(), batch, tx) + .unwrap_add_cost(&mut cost); + let element = cost_return_on_error!( + &mut cost, + Element::get_from_storage(&parent_storage, parent_key, grove_version).map_err(|e| { + Error::InvalidParentLayerPath(format!( + "could not get key {} for parent {:?} of subtree: {}", + hex::encode(parent_key), + DebugByteVectors(parent_path.to_vec()), + e + )) }) - } else { - use crate::util::storage_context_with_parent_optional_tx; - storage_context_with_parent_optional_tx!( - &mut $cost, - $db, - $path, - $batch, - $transaction, + ); + let is_sum_tree = element.is_sum_tree(); + if let Element::Tree(root_key, _) | Element::SumTree(root_key, ..) = element { + Merk::open_layered_with_root_key( storage, root_key, is_sum_tree, - $grove_version, - { - #[allow(unused_mut)] - let mut $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version, - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* - } + Some(&Element::value_defined_cost_for_serialized_value), + grove_version, ) - } - }; + .map_err(|_| { + Error::CorruptedData("cannot open a subtree with given root key".to_owned()) + }) + .add_cost(cost) + } else { + Err(Error::CorruptedPath( + "cannot open a subtree as parent exists but is not a tree".to_string(), + )) + .wrap_with_cost(cost) + } + } else { + Merk::open_base( + storage, + false, + Some(&Element::value_defined_cost_for_serialized_value), + grove_version, + ) + .map_err(|_| Error::CorruptedData("cannot open a the root subtree".to_owned())) + .add_cost(cost) + } } -/// Macro to execute same piece of code on Merk with varying storage -/// contexts. -macro_rules! merk_optional_tx_internal_error { - ( - &mut $cost:ident, - $db:expr, - $path:expr, - $batch:expr, - $transaction:ident, - $subtree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - if $path.is_root() { - use crate::util::storage_context_optional_tx; - storage_context_optional_tx!( - $db, - ::grovedb_path::SubtreePath::empty(), - $batch, - $transaction, - storage, - { - let $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_base( - storage.unwrap_add_cost(&mut $cost), - false, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* - }) - } else { - use crate::util::storage_context_with_parent_optional_tx_internal_error; - storage_context_with_parent_optional_tx_internal_error!( - &mut $cost, - $db, - $path, - $batch, - $transaction, - storage, - root_key, - is_sum_tree, - $grove_version, - { - #[allow(unused_mut)] - let mut $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version, - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* - } - ) - } - }; +// /// Wrapper type that keeps path and key used to perform an operation. +// pub(crate) struct WithOrigin<'b, 'k, B, T> { +// pub(crate) path: SubtreePath<'b, B>, +// pub(crate) key: &'k [u8], +// pub(crate) value: T, +// } + +// impl<'b, 'k, B, T> WithOrigin<'b, 'k, B, T> { +// pub(crate) fn run( +// path: SubtreePath<'b, B>, +// key: &'k [u8], +// f: impl FnOnce(SubtreePath<'b, B>, &'k [u8]) -> T, +// ) -> Self { +// WithOrigin { +// path: path.clone(), +// key, +// value: f(path, key), +// } +// } +// } + +// impl<'b, 'k, B, T, E> WithOrigin<'b, 'k, B, CostResult> { +// pub(crate) fn into_cost_result(self) -> CostResult, E> { let mut cost = Default::default(); +// let value = cost_return_on_error!(&mut cost, self.value); +// Ok(WithOrigin { +// value, +// path: self.path, +// key: self.key, +// }) +// .wrap_with_cost(cost) +// } +// } + +pub(crate) struct ResolvedReference<'db, 'b, 'c, B> { + pub target_merk: MerkHandle<'db, 'c>, + pub target_path: SubtreePathBuilder<'b, B>, + pub target_key: Vec, + pub target_element: Element, + pub target_node_value_hash: CryptoHash, } -/// Macro to execute same piece of code on Merk with varying storage -/// contexts. -macro_rules! merk_optional_tx_path_not_empty { - ( - &mut $cost:ident, - $db:expr, - $path:expr, - $batch:expr, - $transaction:ident, - $subtree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - { - use crate::util::storage_context_with_parent_optional_tx; - storage_context_with_parent_optional_tx!( - &mut $cost, - $db, - $path, - $batch, - $transaction, - storage, - root_key, - is_sum_tree, - $grove_version, - { - #[allow(unused_mut)] - let mut $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_layered_with_root_key( - storage, - root_key, - is_sum_tree, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version, - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* - } - ) +pub(crate) fn follow_reference<'db, 'b, 'c, B: AsRef<[u8]>>( + merk_cache: &'c MerkCache<'db, 'b, B>, + path: SubtreePathBuilder<'b, B>, + key: &[u8], + ref_path: ReferencePathType, +) -> CostResult, Error> { + check_grovedb_v0_with_cost!( + "follow_reference", + merk_cache + .version + .grovedb_versions + .operations + .get + .follow_reference + ); + + let mut cost = OperationCost::default(); + + let mut hops_left = MAX_REFERENCE_HOPS; + let mut visited = HashSet::new(); + + let mut qualified_path = path.clone(); + qualified_path.push_segment(key); + + visited.insert(qualified_path); + + let mut current_path = path; + let mut current_key = key.to_vec(); + let mut current_ref = ref_path; + + while hops_left > 0 { + let referred_qualified_path = cost_return_on_error_no_add!( + cost, + current_ref.absolute_qualified_path(current_path, ¤t_key) + ); + + if !visited.insert(referred_qualified_path.clone()) { + return Err(Error::CyclicReference).wrap_with_cost(cost); + } + + let Some((referred_path, referred_key)) = referred_qualified_path.derive_parent_owned() + else { + return Err(Error::InvalidCodeExecution("empty reference")).wrap_with_cost(cost); + }; + + let mut referred_merk = + cost_return_on_error!(&mut cost, merk_cache.get_merk(referred_path.clone())); + let (element, value_hash) = cost_return_on_error!( + &mut cost, + referred_merk + .for_merk(|m| { + Element::get_with_value_hash(m, &referred_key, true, merk_cache.version) + }) + .map_err(|e| match e { + Error::PathKeyNotFound(s) => Error::CorruptedReferencePathKeyNotFound(s), + e => e, + }) + ); + + match element { + Element::Reference(ref_path, ..) => { + current_path = referred_path; + current_key = referred_key; + current_ref = ref_path; + hops_left -= 1; + } + e => { + return Ok(ResolvedReference { + target_merk: referred_merk, + target_path: referred_path, + target_key: referred_key, + target_element: e, + target_node_value_hash: value_hash, + }) + .wrap_with_cost(cost) + } + } } - }; + + Err(Error::ReferenceLimit).wrap_with_cost(cost) } -/// Macro to execute same piece of code on Merk with varying storage -/// contexts. -macro_rules! root_merk_optional_tx { - ( - &mut $cost:ident, - $db:expr, - $batch:expr, - $transaction:ident, - $subtree:ident, - $grove_version:ident, - { $($body:tt)* } - ) => { - { - use crate::util::storage_context_optional_tx; - storage_context_optional_tx!( - $db, - ::grovedb_path::SubtreePath::empty(), - $batch, - $transaction, - storage, - { - let $subtree = cost_return_on_error!( - &mut $cost, - ::grovedb_merk::Merk::open_base( - storage.unwrap_add_cost(&mut $cost), - false, - Some(&Element::value_defined_cost_for_serialized_value), - $grove_version, - ).map(|merk_res| - merk_res - .map_err(|_| crate::Error::CorruptedData( - "cannot open a subtree".to_owned() - )) - ) - ); - $($body)* - }) - } +/// Follow references stopping at the immediate element without following +/// further. +pub(crate) fn follow_reference_once<'db, 'b, 'c, B: AsRef<[u8]>>( + merk_cache: &'c MerkCache<'db, 'b, B>, + path: SubtreePathBuilder<'b, B>, + key: &[u8], + ref_path: ReferencePathType, +) -> CostResult, Error> { + check_grovedb_v0_with_cost!( + "follow_reference_once", + merk_cache + .version + .grovedb_versions + .operations + .get + .follow_reference_once + ); + + let mut cost = OperationCost::default(); + + let referred_qualified_path = + cost_return_on_error_no_add!(cost, ref_path.absolute_qualified_path(path.clone(), key)); + + let Some((referred_path, referred_key)) = referred_qualified_path.derive_parent_owned() else { + return Err(Error::InvalidCodeExecution("empty reference")).wrap_with_cost(cost); }; + + if path == referred_path && key == referred_key { + return Err(Error::CyclicReference).wrap_with_cost(cost); + } + + let mut referred_merk = + cost_return_on_error!(&mut cost, merk_cache.get_merk(referred_path.clone())); + let (element, value_hash) = cost_return_on_error!( + &mut cost, + referred_merk + .for_merk(|m| { + Element::get_with_value_hash(m, &referred_key, true, merk_cache.version) + }) + .map_err(|e| match e { + Error::PathKeyNotFound(s) => Error::CorruptedReferencePathKeyNotFound(s), + e => e, + }) + ); + + Ok(ResolvedReference { + target_merk: referred_merk, + target_path: referred_path, + target_key: referred_key, + target_element: element, + target_node_value_hash: value_hash, + }) + .wrap_with_cost(cost) } -pub(crate) use merk_optional_tx; -pub(crate) use merk_optional_tx_internal_error; -pub(crate) use merk_optional_tx_path_not_empty; -pub(crate) use meta_storage_context_optional_tx; -pub(crate) use root_merk_optional_tx; -pub(crate) use storage_context_optional_tx; -pub(crate) use storage_context_with_parent_optional_tx; -pub(crate) use storage_context_with_parent_optional_tx_internal_error; +// #[cfg(test)] +// mod tests { +// use pretty_assertions::assert_eq; + +// use super::*; +// use crate::tests::{make_deep_tree, TEST_LEAF}; + +// #[test] +// fn with_origin() { +// let version = GroveVersion::latest(); +// let db = make_deep_tree(&version); + +// let wo = WithOrigin::run( +// SubtreePath::from(&[TEST_LEAF, b"innertree"]), +// b"key1", +// |path, key| db.get(path, key, None, &version), +// ); + +// assert_eq!(wo.path, SubtreePath::from(&[TEST_LEAF, b"innertree"])); +// assert_eq!(wo.key, b"key1"); + +// let with_origin_cost_result: CostResult<_, _> = +// wo.into_cost_result(); + +// assert_eq!( +// with_origin_cost_result.unwrap().unwrap().value, +// Element::Item(b"value1".to_vec(), None) +// ); +// } +// } diff --git a/grovedb/src/visualize.rs b/grovedb/src/visualize.rs index 39cf3432b..8b531cc08 100644 --- a/grovedb/src/visualize.rs +++ b/grovedb/src/visualize.rs @@ -36,13 +36,12 @@ use bincode::{ }; use grovedb_merk::{Merk, VisualizeableMerk}; use grovedb_path::SubtreePathBuilder; -use grovedb_storage::StorageContext; +use grovedb_storage::{Storage, StorageContext}; use grovedb_version::version::GroveVersion; use grovedb_visualize::{visualize_stdout, Drawer, Visualize}; use crate::{ - element::Element, reference_path::ReferencePathType, util::storage_context_optional_tx, - GroveDb, TransactionArg, + element::Element, reference_path::ReferencePathType, util::TxRef, GroveDb, TransactionArg, }; impl Visualize for Element { @@ -192,35 +191,40 @@ impl GroveDb { ) -> Result> { drawer.down(); - storage_context_optional_tx!(self.db, (&path).into(), None, transaction, storage, { - let mut iter = Element::iterator(storage.unwrap().raw_iter()).unwrap(); - while let Some((key, element)) = iter - .next_element(grove_version) - .unwrap() - .expect("cannot get next element") - { - drawer.write(b"\n[key: ")?; - drawer = key.visualize(drawer)?; - drawer.write(b" ")?; - match element { - Element::Tree(..) => { - drawer.write(b"Merk root is: ")?; - drawer = element.visualize(drawer)?; - drawer.down(); - drawer = self.draw_subtree( - drawer, - path.derive_owned_with_child(key), - transaction, - grove_version, - )?; - drawer.up(); - } - other => { - drawer = other.visualize(drawer)?; - } + let tx = TxRef::new(&self.db, transaction); + + let storage = self + .db + .get_transactional_storage_context((&path).into(), None, tx.as_ref()) + .unwrap(); + + let mut iter = Element::iterator(storage.raw_iter()).unwrap(); + while let Some((key, element)) = iter + .next_element(grove_version) + .unwrap() + .expect("cannot get next element") + { + drawer.write(b"\n[key: ")?; + drawer = key.visualize(drawer)?; + drawer.write(b" ")?; + match element { + Element::Tree(..) => { + drawer.write(b"Merk root is: ")?; + drawer = element.visualize(drawer)?; + drawer.down(); + drawer = self.draw_subtree( + drawer, + path.derive_owned_with_child(key), + transaction, + grove_version, + )?; + drawer.up(); + } + other => { + drawer = other.visualize(drawer)?; } } - }); + } drawer.up(); Ok(drawer) diff --git a/merk/src/merk/meta.rs b/merk/src/merk/meta.rs new file mode 100644 index 000000000..e967dfd23 --- /dev/null +++ b/merk/src/merk/meta.rs @@ -0,0 +1,111 @@ +//! Metadata access for Merk trees + +use std::collections::hash_map::Entry; + +use grovedb_costs::{CostResult, CostsExt}; +use grovedb_storage::StorageContext; + +use super::Merk; +use crate::Error; + +impl<'db, S: StorageContext<'db>> Merk { + /// Get metadata for the Merk under `key`. + pub fn get_meta<'s>(&'s mut self, key: Vec) -> CostResult, Error> { + match self.meta_cache.entry(key) { + Entry::Occupied(e) => Ok(e.into_mut().as_deref()).wrap_with_cost(Default::default()), + Entry::Vacant(e) => self + .storage + .get_meta(e.key()) + .map_ok(|b| e.insert(b).as_deref()) + .map_err(Error::StorageError), + } + } + + /// Set metadata under `key`. This doesn't affect the state (root hash). + pub fn put_meta(&mut self, key: Vec, value: Vec) -> CostResult<(), Error> { + self.storage + .put_meta(&key, &value, None) + .map_ok(|_| { + self.meta_cache.insert(key, Some(value)); + }) + .map_err(Error::StorageError) + } + + /// Delete metadata under `key`. + pub fn delete_meta(&mut self, key: &[u8]) -> CostResult<(), Error> { + self.storage + .delete_meta(&key, None) + .map_ok(|_| { + self.meta_cache.remove(key); + }) + .map_err(Error::StorageError) + } +} + +#[cfg(test)] +mod tests { + use grovedb_costs::OperationCost; + use grovedb_version::version::GroveVersion; + + use crate::test_utils::TempMerk; + + #[test] + fn meta_storage_data_retrieval() { + let version = GroveVersion::latest(); + let mut merk = TempMerk::new(&version); + + merk.put_meta(b"key".to_vec(), b"value".to_vec()) + .unwrap() + .unwrap(); + + let mut cost: OperationCost = Default::default(); + assert_eq!( + merk.get_meta(b"key".to_vec()) + .unwrap_add_cost(&mut cost) + .unwrap(), + Some(b"value".as_slice()) + ); + assert!(cost.is_nothing()); + } + + #[test] + fn meta_storage_works_uncommited() { + let version = GroveVersion::latest(); + let mut merk = TempMerk::new(&version); + + let mut cost_1: OperationCost = Default::default(); + assert!(merk + .get_meta(b"key".to_vec()) + .unwrap_add_cost(&mut cost_1) + .unwrap() + .is_none()); + assert!(!cost_1.is_nothing()); + + let mut cost_2: OperationCost = Default::default(); + assert!(merk + .get_meta(b"key".to_vec()) + .unwrap_add_cost(&mut cost_2) + .unwrap() + .is_none()); + assert!(cost_2.is_nothing()); + } + + #[test] + fn meta_storage_deletion() { + let version = GroveVersion::latest(); + let mut merk = TempMerk::new(&version); + + merk.put_meta(b"key".to_vec(), b"value".to_vec()) + .unwrap() + .unwrap(); + + assert_eq!( + merk.get_meta(b"key".to_vec()).unwrap().unwrap(), + Some(b"value".as_slice()) + ); + + merk.delete_meta(b"key").unwrap().unwrap(); + + assert!(merk.get_meta(b"key".to_vec()).unwrap().unwrap().is_none()); + } +} diff --git a/merk/src/merk/mod.rs b/merk/src/merk/mod.rs index ee0deccc3..b5d9e01ba 100644 --- a/merk/src/merk/mod.rs +++ b/merk/src/merk/mod.rs @@ -37,6 +37,7 @@ pub mod apply; pub mod clear; pub mod committer; pub mod get; +mod meta; pub mod open; pub mod prove; pub mod restore; @@ -44,7 +45,7 @@ pub mod source; use std::{ cell::Cell, - collections::{BTreeMap, BTreeSet, LinkedList}, + collections::{BTreeMap, BTreeSet, HashMap, LinkedList}, fmt, }; @@ -253,6 +254,9 @@ pub struct Merk { pub merk_type: MerkType, /// Is sum tree? pub is_sum_tree: bool, + /// Metadata storage cache. As well as trees work in-memory until committed, + /// meta KV storage shall be able to work the same way. + meta_cache: HashMap, Option>>, } impl fmt::Debug for Merk { @@ -378,7 +382,7 @@ where // update pointer to root node cost_return_on_error_no_add!( - &inner_cost, + inner_cost, batch .put_root(ROOT_KEY_KEY, tree_key, costs) .map_err(CostsError) @@ -414,7 +418,7 @@ where for (key, maybe_sum_tree_cost, maybe_value, storage_cost) in to_batch { if let Some((value, left_size, right_size)) = maybe_value { cost_return_on_error_no_add!( - &cost, + cost, batch .put( &key, @@ -432,7 +436,7 @@ where for (key, value, storage_cost) in aux { match value { Op::Put(value, ..) => cost_return_on_error_no_add!( - &cost, + cost, batch .put_aux(key, value, storage_cost.clone()) .map_err(CostsError) @@ -440,7 +444,7 @@ where Op::Delete => batch.delete_aux(key, storage_cost.clone()), _ => { cost_return_on_error_no_add!( - &cost, + cost, Err(Error::InvalidOperation( "only put and delete allowed for aux storage" )) @@ -754,7 +758,7 @@ mod test { use grovedb_path::SubtreePath; use grovedb_storage::{ - rocksdb_storage::{PrefixedRocksDbStorageContext, RocksDbStorage}, + rocksdb_storage::{PrefixedRocksDbTransactionContext, RocksDbStorage}, RawIterator, Storage, StorageBatch, StorageContext, }; use grovedb_version::version::GroveVersion; @@ -987,9 +991,10 @@ mod test { let tmp_dir = TempDir::new().expect("cannot open tempdir"); let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1013,9 +1018,10 @@ mod test { let tmp_dir = TempDir::new().expect("cannot open tempdir"); let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1034,7 +1040,7 @@ mod test { fn reopen() { let grove_version = GroveVersion::latest(); fn collect( - mut node: RefWalker>, + mut node: RefWalker>, nodes: &mut Vec>, ) { let grove_version = GroveVersion::latest(); @@ -1069,9 +1075,10 @@ mod test { let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), Some(&batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1085,12 +1092,12 @@ mod test { .unwrap(); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .expect("cannot commit batch"); let merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1104,14 +1111,19 @@ mod test { let mut nodes = vec![]; collect(walker, &mut nodes); + storage + .commit_transaction(tx) + .unwrap() + .expect("unable to commit transaction"); nodes }; let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); + let tx = storage.start_transaction(); let merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1129,7 +1141,7 @@ mod test { } type PrefixedStorageIter<'db, 'ctx> = - &'ctx mut as StorageContext<'db>>::RawIterator; + &'ctx mut as StorageContext<'db>>::RawIterator; #[test] fn reopen_iter() { @@ -1149,9 +1161,10 @@ mod test { let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), Some(&batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1170,9 +1183,10 @@ mod test { .expect("cannot commit batch"); let mut nodes = vec![]; + let tx = storage.start_transaction(); let merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1185,9 +1199,10 @@ mod test { }; let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); + let tx = storage.start_transaction(); let merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1209,9 +1224,10 @@ mod test { let storage = RocksDbStorage::default_rocksdb_with_path(tmp_dir.path()) .expect("cannot open rocksdb storage"); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), Some(&batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -1269,13 +1285,13 @@ mod test { assert_eq!(result, Some(b"b".to_vec())); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .expect("cannot commit batch"); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, diff --git a/merk/src/merk/open.rs b/merk/src/merk/open.rs index c8646afaf..a266dda6b 100644 --- a/merk/src/merk/open.rs +++ b/merk/src/merk/open.rs @@ -22,6 +22,7 @@ where storage, merk_type, is_sum_tree, + meta_cache: Default::default(), } } @@ -40,6 +41,7 @@ where storage, merk_type: StandaloneMerk, is_sum_tree, + meta_cache: Default::default(), }; merk.load_base_root(value_defined_cost_fn, grove_version) @@ -61,6 +63,7 @@ where storage, merk_type: BaseMerk, is_sum_tree, + meta_cache: Default::default(), }; merk.load_base_root(value_defined_cost_fn, grove_version) @@ -83,6 +86,7 @@ where storage, merk_type: LayeredMerk, is_sum_tree, + meta_cache: Default::default(), }; merk.load_root(value_defined_cost_fn, grove_version) @@ -112,9 +116,14 @@ mod test { let test_prefix = [b"ayy"]; let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let mut merk = Merk::open_base( storage - .get_storage_context(SubtreePath::from(test_prefix.as_ref()), Some(&batch)) + .get_transactional_storage_context( + SubtreePath::from(test_prefix.as_ref()), + Some(&batch), + &tx, + ) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -135,13 +144,17 @@ mod test { let root_hash = merk.root_hash(); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .expect("cannot commit batch"); let merk = Merk::open_base( storage - .get_storage_context(SubtreePath::from(test_prefix.as_ref()), None) + .get_transactional_storage_context( + SubtreePath::from(test_prefix.as_ref()), + None, + &tx, + ) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -157,10 +170,11 @@ mod test { let grove_version = GroveVersion::latest(); let storage = TempStorage::new(); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let merk_fee_context = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), Some(&batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(&batch), &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, @@ -184,13 +198,13 @@ mod test { .expect("apply failed"); storage - .commit_multi_context_batch(batch, None) + .commit_multi_context_batch(batch, Some(&tx)) .unwrap() .expect("cannot commit batch"); let merk_fee_context = Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, &tx) .unwrap(), false, None::<&fn(&[u8], &GroveVersion) -> Option>, diff --git a/merk/src/merk/restore.rs b/merk/src/merk/restore.rs index 1082e80b8..3fc393ed2 100644 --- a/merk/src/merk/restore.rs +++ b/merk/src/merk/restore.rs @@ -549,7 +549,7 @@ mod tests { use grovedb_storage::{ rocksdb_storage::{ test_utils::TempStorage, PrefixedRocksDbImmediateStorageContext, - PrefixedRocksDbStorageContext, + PrefixedRocksDbTransactionContext, }, RawIterator, Storage, }; @@ -574,7 +574,7 @@ mod tests { Op::Push(Node::KV(vec![3], vec![3])), Op::Parent, ]; - assert!(Restorer::::verify_chunk( + assert!(Restorer::::verify_chunk( non_avl_tree_proof, &[0; 32], &None @@ -586,7 +586,7 @@ mod tests { fn test_chunk_verification_only_kv_feature_and_hash() { // should not accept kv let invalid_chunk_proof = vec![Op::Push(Node::KV(vec![1], vec![1]))]; - let verification_result = Restorer::::verify_chunk( + let verification_result = Restorer::::verify_chunk( invalid_chunk_proof, &[0; 32], &None, @@ -600,7 +600,7 @@ mod tests { // should not accept kvhash let invalid_chunk_proof = vec![Op::Push(Node::KVHash([0; 32]))]; - let verification_result = Restorer::::verify_chunk( + let verification_result = Restorer::::verify_chunk( invalid_chunk_proof, &[0; 32], &None, @@ -614,7 +614,7 @@ mod tests { // should not accept kvdigest let invalid_chunk_proof = vec![Op::Push(Node::KVDigest(vec![0], [0; 32]))]; - let verification_result = Restorer::::verify_chunk( + let verification_result = Restorer::::verify_chunk( invalid_chunk_proof, &[0; 32], &None, @@ -628,7 +628,7 @@ mod tests { // should not accept kvvaluehash let invalid_chunk_proof = vec![Op::Push(Node::KVValueHash(vec![0], vec![0], [0; 32]))]; - let verification_result = Restorer::::verify_chunk( + let verification_result = Restorer::::verify_chunk( invalid_chunk_proof, &[0; 32], &None, @@ -642,7 +642,7 @@ mod tests { // should not accept kvrefvaluehash let invalid_chunk_proof = vec![Op::Push(Node::KVRefValueHash(vec![0], vec![0], [0; 32]))]; - let verification_result = Restorer::::verify_chunk( + let verification_result = Restorer::::verify_chunk( invalid_chunk_proof, &[0; 32], &None, diff --git a/merk/src/proofs/tree.rs b/merk/src/proofs/tree.rs index 16655a6dc..63ac556c4 100644 --- a/merk/src/proofs/tree.rs +++ b/merk/src/proofs/tree.rs @@ -379,11 +379,11 @@ where } for op in ops { - match cost_return_on_error_no_add!(&cost, op) { + match cost_return_on_error_no_add!(cost, op) { Op::Parent => { let (mut parent, child) = ( - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), ); cost_return_on_error!( &mut cost, @@ -400,8 +400,8 @@ where } Op::Child => { let (child, mut parent) = ( - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), ); cost_return_on_error!( &mut cost, @@ -418,8 +418,8 @@ where } Op::ParentInverted => { let (mut parent, child) = ( - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), ); cost_return_on_error!( &mut cost, @@ -436,8 +436,8 @@ where } Op::ChildInverted => { let (child, mut parent) = ( - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), - cost_return_on_error_no_add!(&cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), + cost_return_on_error_no_add!(cost, try_pop(&mut stack)), ); cost_return_on_error!( &mut cost, @@ -470,7 +470,7 @@ where maybe_last_key = Some(key.clone()); } - cost_return_on_error_no_add!(&cost, visit_node(&node)); + cost_return_on_error_no_add!(cost, visit_node(&node)); let tree: Tree = node.into(); stack.push(tree); @@ -493,7 +493,7 @@ where maybe_last_key = Some(key.clone()); } - cost_return_on_error_no_add!(&cost, visit_node(&node)); + cost_return_on_error_no_add!(cost, visit_node(&node)); let tree: Tree = node.into(); stack.push(tree); diff --git a/merk/src/test_utils/mod.rs b/merk/src/test_utils/mod.rs index 45beda4fe..e21736d1c 100644 --- a/merk/src/test_utils/mod.rs +++ b/merk/src/test_utils/mod.rs @@ -311,14 +311,15 @@ pub fn make_tree_seq_with_start_key( pub fn empty_path_merk<'db, S>( storage: &'db S, batch: &'db StorageBatch, + tx: &'db >::Transaction, grove_version: &GroveVersion, -) -> Merk<>::BatchStorageContext> +) -> Merk<>::BatchTransactionalStorageContext> where S: Storage<'db>, { Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), Some(batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(batch), tx) .unwrap(), false, None:: Option>, @@ -331,14 +332,15 @@ where /// Shortcut to open a Merk for read only pub fn empty_path_merk_read_only<'db, S>( storage: &'db S, + tx: &'db >::Transaction, grove_version: &GroveVersion, -) -> Merk<>::BatchStorageContext> +) -> Merk<>::BatchTransactionalStorageContext> where S: Storage<'db>, { Merk::open_base( storage - .get_storage_context(SubtreePath::empty(), None) + .get_transactional_storage_context(SubtreePath::empty(), None, tx) .unwrap(), false, None:: Option>, diff --git a/merk/src/test_utils/temp_merk.rs b/merk/src/test_utils/temp_merk.rs index 69e5b5550..60f9986fe 100644 --- a/merk/src/test_utils/temp_merk.rs +++ b/merk/src/test_utils/temp_merk.rs @@ -32,11 +32,11 @@ use std::ops::{Deref, DerefMut}; use grovedb_path::SubtreePath; -use grovedb_storage::StorageBatch; #[cfg(feature = "full")] +use grovedb_storage::{rocksdb_storage::test_utils::TempStorage, Storage}; use grovedb_storage::{ - rocksdb_storage::{test_utils::TempStorage, PrefixedRocksDbStorageContext}, - Storage, + rocksdb_storage::{PrefixedRocksDbTransactionContext, RocksDbStorage}, + StorageBatch, }; use grovedb_version::version::GroveVersion; @@ -49,7 +49,8 @@ use crate::Merk; pub struct TempMerk { storage: &'static TempStorage, batch: &'static StorageBatch, - merk: Merk>, + merk: Merk>, + tx: &'static >::Transaction, } #[cfg(feature = "full")] @@ -59,9 +60,10 @@ impl TempMerk { pub fn new(grove_version: &GroveVersion) -> Self { let storage = Box::leak(Box::new(TempStorage::new())); let batch = Box::leak(Box::new(StorageBatch::new())); + let tx = Box::leak(Box::new(storage.start_transaction())); let context = storage - .get_storage_context(SubtreePath::empty(), Some(batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(batch), tx) .unwrap(); let merk = Merk::open_base( @@ -76,20 +78,32 @@ impl TempMerk { storage, merk, batch, + tx, } } /// Commits pending batch operations. pub fn commit(&mut self, grove_version: &GroveVersion) { - let batch = unsafe { Box::from_raw(self.batch as *const _ as *mut StorageBatch) }; + let batch: Box = + unsafe { Box::from_raw(self.batch as *const _ as *mut StorageBatch) }; + let tx: Box<>::Transaction> = unsafe { + Box::from_raw( + self.tx as *const _ as *mut >::Transaction, + ) + }; self.storage - .commit_multi_context_batch(*batch, None) + .commit_multi_context_batch(*batch, Some(self.tx)) .unwrap() .expect("unable to commit batch"); + self.storage + .commit_transaction(*tx) + .unwrap() + .expect("unable to commit transaction"); self.batch = Box::leak(Box::new(StorageBatch::new())); + self.tx = Box::leak(Box::new(self.storage.start_transaction())); let context = self .storage - .get_storage_context(SubtreePath::empty(), Some(self.batch)) + .get_transactional_storage_context(SubtreePath::empty(), Some(self.batch), self.tx) .unwrap(); self.merk = Merk::open_base( context, @@ -107,7 +121,13 @@ impl Drop for TempMerk { fn drop(&mut self) { unsafe { let batch = Box::from_raw(self.batch as *const _ as *mut StorageBatch); - let _ = self.storage.commit_multi_context_batch(*batch, None); + + let tx: Box<>::Transaction> = Box::from_raw( + self.tx as *const _ as *mut >::Transaction, + ); + + let _ = self.storage.commit_multi_context_batch(*batch, Some(&tx)); + let _ = self.storage.commit_transaction(*tx).unwrap(); drop(Box::from_raw(self.storage as *const _ as *mut TempStorage)); } } @@ -122,16 +142,16 @@ impl Default for TempMerk { #[cfg(feature = "full")] impl Deref for TempMerk { - type Target = Merk>; + type Target = Merk>; - fn deref(&self) -> &Merk> { + fn deref(&self) -> &Merk> { &self.merk } } #[cfg(feature = "full")] impl DerefMut for TempMerk { - fn deref_mut(&mut self) -> &mut Merk> { + fn deref_mut(&mut self) -> &mut Merk> { &mut self.merk } } diff --git a/merk/src/tree/encoding.rs b/merk/src/tree/encoding.rs index cd10937d9..11bd906a7 100644 --- a/merk/src/tree/encoding.rs +++ b/merk/src/tree/encoding.rs @@ -52,7 +52,7 @@ impl TreeNode { let tree_bytes = cost_return_on_error!(&mut cost, storage.get(&key).map_err(StorageError)); let tree_opt = cost_return_on_error_no_add!( - &cost, + cost, tree_bytes .map(|x| TreeNode::decode_raw( &x, diff --git a/merk/src/tree/mod.rs b/merk/src/tree/mod.rs index 91eebf52a..7008f538a 100644 --- a/merk/src/tree/mod.rs +++ b/merk/src/tree/mod.rs @@ -716,7 +716,7 @@ impl TreeNode { // in this case there is a possibility that the client would want to update the // element flags based on the change of values cost_return_on_error_no_add!( - &cost, + cost, self.just_in_time_tree_node_value_update( old_specialized_cost, get_temp_new_value_with_old_flags, @@ -772,7 +772,7 @@ impl TreeNode { // in this case there is a possibility that the client would want to update the // element flags based on the change of values cost_return_on_error_no_add!( - &cost, + cost, self.just_in_time_tree_node_value_update( old_specialized_cost, get_temp_new_value_with_old_flags, @@ -826,7 +826,7 @@ impl TreeNode { // in this case there is a possibility that the client would want to update the // element flags based on the change of values cost_return_on_error_no_add!( - &cost, + cost, self.just_in_time_tree_node_value_update( old_specialized_cost, get_temp_new_value_with_old_flags, @@ -888,7 +888,7 @@ impl TreeNode { // in this case there is a possibility that the client would want to update the // element flags based on the change of values cost_return_on_error_no_add!( - &cost, + cost, self.just_in_time_tree_node_value_update( old_specialized_cost, get_temp_new_value_with_old_flags, @@ -971,7 +971,7 @@ impl TreeNode { } } - cost_return_on_error_no_add!(&cost, c.write(self, old_specialized_cost,)); + cost_return_on_error_no_add!(cost, c.write(self, old_specialized_cost,)); // println!("done committing {}", std::str::from_utf8(self.key()).unwrap()); diff --git a/merk/src/tree/ops.rs b/merk/src/tree/ops.rs index 3e10b2c81..5fdb625fc 100644 --- a/merk/src/tree/ops.rs +++ b/merk/src/tree/ops.rs @@ -514,13 +514,13 @@ where Delete => self.tree().inner.kv.value_byte_cost_size(), DeleteLayered | DeleteLayeredMaybeSpecialized => { cost_return_on_error_no_add!( - &cost, + cost, old_specialized_cost(&key_vec, value) ) } DeleteMaybeSpecialized => { cost_return_on_error_no_add!( - &cost, + cost, old_specialized_cost(&key_vec, value) ) } @@ -534,7 +534,7 @@ where prefixed_key_len + prefixed_key_len.required_space() as u32; let value = self.tree().value_ref(); cost_return_on_error_no_add!( - &cost, + cost, section_removal_bytes(value, total_key_len, old_cost) ) }; diff --git a/merk/src/tree/walk/mod.rs b/merk/src/tree/walk/mod.rs index 4b67bb609..8fdf0be44 100644 --- a/merk/src/tree/walk/mod.rs +++ b/merk/src/tree/walk/mod.rs @@ -230,7 +230,7 @@ where ) -> CostResult { let mut cost = OperationCost::default(); cost_return_on_error_no_add!( - &cost, + cost, self.tree.own_result(|t| t .put_value( value, @@ -275,7 +275,7 @@ where ) -> CostResult { let mut cost = OperationCost::default(); cost_return_on_error_no_add!( - &cost, + cost, self.tree.own_result(|t| t .put_value_with_fixed_cost( value, @@ -321,7 +321,7 @@ where ) -> CostResult { let mut cost = OperationCost::default(); cost_return_on_error_no_add!( - &cost, + cost, self.tree.own_result(|t| t .put_value_and_reference_value_hash( value, @@ -368,7 +368,7 @@ where ) -> CostResult { let mut cost = OperationCost::default(); cost_return_on_error_no_add!( - &cost, + cost, self.tree.own_result(|t| t .put_value_with_reference_value_hash_and_value_cost( value, diff --git a/path/Cargo.toml b/path/Cargo.toml index 92417664f..0d4ab183d 100644 --- a/path/Cargo.toml +++ b/path/Cargo.toml @@ -9,3 +9,5 @@ documentation = "https://docs.rs/grovedb-path" repository = "https://github.com/dashpay/grovedb" [dependencies] +hex = "0.4.3" +itertools = "0.13.0" diff --git a/path/src/subtree_path.rs b/path/src/subtree_path.rs index 437f911af..b754b91ed 100644 --- a/path/src/subtree_path.rs +++ b/path/src/subtree_path.rs @@ -34,7 +34,11 @@ //! combined with it's various `From` implementations it can cover slices, owned //! subtree paths and other path references if use as generic [Into]. -use std::hash::{Hash, Hasher}; +use std::{ + cmp, + fmt::{self, Display}, + hash::{Hash, Hasher}, +}; use crate::{ subtree_path_builder::{SubtreePathBuilder, SubtreePathRelative}, @@ -48,6 +52,34 @@ pub struct SubtreePath<'b, B> { pub(crate) ref_variant: SubtreePathInner<'b, B>, } +impl<'b, B: AsRef<[u8]>> Display for SubtreePath<'b, B> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let path = self.to_vec(); + + fn fmt_segment(s: impl AsRef<[u8]>) -> String { + let bytes = s.as_ref(); + let hex_str = hex::encode(bytes); + let utf8_str = String::from_utf8(bytes.to_vec()); + let mut result = format!("h:{hex_str}"); + if let Ok(s) = utf8_str { + result.push_str("/s:"); + result.push_str(&s); + } + result + } + + f.write_str("[")?; + + for s in itertools::intersperse(path.into_iter().map(fmt_segment), ", ".to_owned()) { + f.write_str(&s)?; + } + + f.write_str("]")?; + + Ok(()) + } +} + /// Wrapped inner representation of subtree path ref. #[derive(Debug)] pub(crate) enum SubtreePathInner<'b, B> { @@ -78,6 +110,77 @@ where } } +/// First and foremost, the order of subtree paths is dictated by their lengths. +/// Therefore, those subtrees closer to the root will come first. The rest it +/// can guarantee is to be free of false equality; however, seemingly unrelated +/// subtrees can come one after another if they share the same length, which was +/// (not) done for performance reasons. +impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePath<'bl, BL> +where + BL: AsRef<[u8]>, + BR: AsRef<[u8]>, +{ + fn partial_cmp(&self, other: &SubtreePath<'br, BR>) -> Option { + let iter_a = self.clone().into_reverse_iter(); + let iter_b = other.clone().into_reverse_iter(); + + Some( + iter_a + .len() + .cmp(&iter_b.len()) + .reverse() + .then_with(|| iter_a.cmp(iter_b)), + ) + } +} + +impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePathBuilder<'bl, BL> +where + BL: AsRef<[u8]>, + BR: AsRef<[u8]>, +{ + fn partial_cmp(&self, other: &SubtreePathBuilder<'br, BR>) -> Option { + let iter_a = self.reverse_iter(); + let iter_b = other.reverse_iter(); + + Some( + iter_a + .len() + .cmp(&iter_b.len()) + .reverse() + .then_with(|| iter_a.cmp(iter_b)), + ) + } +} + +impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePath<'bl, BL> +where + BL: AsRef<[u8]>, + BR: AsRef<[u8]>, +{ + fn partial_cmp(&self, other: &SubtreePathBuilder<'br, BR>) -> Option { + self.partial_cmp(&SubtreePath::from(other)) + } +} + +impl<'bl, BL> Ord for SubtreePath<'bl, BL> +where + BL: AsRef<[u8]>, +{ + fn cmp(&self, other: &Self) -> cmp::Ordering { + self.partial_cmp(other).expect("order is totally defined") + } +} + +impl<'bl, BL> Ord for SubtreePathBuilder<'bl, BL> +where + BL: AsRef<[u8]>, +{ + fn cmp(&self, other: &Self) -> cmp::Ordering { + self.partial_cmp(other).expect("order is totally defined") + } +} + impl<'b, B: AsRef<[u8]>> Eq for SubtreePath<'b, B> {} impl<'b, B> From> for SubtreePath<'b, B> { @@ -174,7 +277,7 @@ impl<'b, B: AsRef<[u8]>> SubtreePath<'b, B> { } /// Get a derived path with a child path segment added. - pub fn derive_owned_with_child<'s, S>(&'b self, segment: S) -> SubtreePathBuilder<'b, B> + pub fn derive_owned_with_child<'s, S>(&self, segment: S) -> SubtreePathBuilder<'b, B> where S: Into>, 's: 'b, @@ -274,4 +377,29 @@ mod tests { assert_eq!(as_vec, reference_vec); assert_eq!(parent.len(), reference_vec.len()); } + + #[test] + fn ordering() { + let path_a: SubtreePath<_> = (&[b"one" as &[u8], b"two", b"three"]).into(); + let path_b = path_a.derive_owned_with_child(b"four"); + let path_c = path_a.derive_owned_with_child(b"notfour"); + let (path_d_parent, _) = path_a.derive_parent().unwrap(); + let path_d = path_d_parent.derive_owned_with_child(b"three"); + + // Same lengths for different paths don't make them equal: + assert!(!matches!( + SubtreePath::from(&path_b).cmp(&SubtreePath::from(&path_c)), + cmp::Ordering::Equal + )); + + // Equal paths made the same way are equal: + assert!(matches!( + path_a.cmp(&SubtreePath::from(&path_d)), + cmp::Ordering::Equal + )); + + // Longer paths come first + assert!(path_a > path_b); + assert!(path_a > path_c); + } } diff --git a/path/src/subtree_path_builder.rs b/path/src/subtree_path_builder.rs index 4ef25f0a1..6ac779775 100644 --- a/path/src/subtree_path_builder.rs +++ b/path/src/subtree_path_builder.rs @@ -46,6 +46,15 @@ pub struct SubtreePathBuilder<'b, B> { pub(crate) relative: SubtreePathRelative<'b>, } +impl<'b, B> Clone for SubtreePathBuilder<'b, B> { + fn clone(&self) -> Self { + SubtreePathBuilder { + base: self.base.clone(), + relative: self.relative.clone(), + } + } +} + /// Hash order is the same as iteration order: from most deep path segment up to /// root. impl<'b, B: AsRef<[u8]>> Hash for SubtreePathBuilder<'b, B> { @@ -97,7 +106,7 @@ impl<'s, 'b, B> From<&'s SubtreePath<'b, B>> for SubtreePathBuilder<'b, B> { } /// Derived subtree path on top of base path. -#[derive(Debug)] +#[derive(Debug, Clone)] pub(crate) enum SubtreePathRelative<'r> { /// Equivalent to the base path. Empty, @@ -149,6 +158,28 @@ impl Default for SubtreePathBuilder<'static, [u8; 0]> { } } +impl<'b, B> SubtreePathBuilder<'b, B> { + /// Makes an owned `SubtreePathBuilder` out of iterator. + pub fn owned_from_iter>(iter: impl IntoIterator) -> Self { + let bytes = iter.into_iter().fold(CompactBytes::new(), |mut bytes, s| { + bytes.add_segment(s.as_ref()); + bytes + }); + + SubtreePathBuilder { + base: SubtreePath { + ref_variant: SubtreePathInner::Slice(&[]), + }, + relative: SubtreePathRelative::Multi(bytes), + } + } + + /// Create an owned version of `SubtreePathBuilder` from `SubtreePath`. + pub fn owned_from_path<'a, S: AsRef<[u8]>>(path: SubtreePath<'a, S>) -> Self { + Self::owned_from_iter(path.to_vec()) + } +} + impl SubtreePathBuilder<'_, B> { /// Returns the length of the subtree path. pub fn len(&self) -> usize { @@ -159,6 +190,24 @@ impl SubtreePathBuilder<'_, B> { pub fn is_empty(&self) -> bool { self.base.is_empty() && self.relative.is_empty() } + + /// Adds path segment in place. + pub fn push_segment(&mut self, segment: &[u8]) { + match &mut self.relative { + SubtreePathRelative::Empty => { + let mut bytes = CompactBytes::new(); + bytes.add_segment(segment); + self.relative = SubtreePathRelative::Multi(bytes); + } + SubtreePathRelative::Single(old_segment) => { + let mut bytes = CompactBytes::new(); + bytes.add_segment(old_segment); + bytes.add_segment(segment); + self.relative = SubtreePathRelative::Multi(bytes); + } + SubtreePathRelative::Multi(bytes) => bytes.add_segment(segment), + } + } } impl<'b, B: AsRef<[u8]>> SubtreePathBuilder<'b, B> { @@ -191,6 +240,37 @@ impl<'b, B: AsRef<[u8]>> SubtreePathBuilder<'b, B> { } } + /// Get a derived path for a parent and a chopped segment. Returned + /// [SubtreePath] will be linked to this [SubtreePath] because it might + /// contain owned data and it has to outlive [SubtreePath]. + pub fn derive_parent_owned(&self) -> Option<(SubtreePathBuilder<'b, B>, Vec)> { + match &self.relative { + SubtreePathRelative::Empty => self + .base + .derive_parent() + .map(|(path, key)| (path.derive_owned(), key.to_vec())), + SubtreePathRelative::Single(relative) => { + Some((self.base.derive_owned(), relative.to_vec())) + } + SubtreePathRelative::Multi(bytes) => { + let mut new_bytes = bytes.clone(); + if let Some(key) = new_bytes.pop_segment() { + Some(( + SubtreePathBuilder { + base: self.base.clone(), + relative: SubtreePathRelative::Multi(new_bytes), + }, + key, + )) + } else { + self.base + .derive_parent() + .map(|(path, key)| (path.derive_owned(), key.to_vec())) + } + } + } + } + /// Get a derived path with a child path segment added. pub fn derive_owned_with_child<'s, S>(&'b self, segment: S) -> SubtreePathBuilder<'b, B> where @@ -203,24 +283,6 @@ impl<'b, B: AsRef<[u8]>> SubtreePathBuilder<'b, B> { } } - /// Adds path segment in place. - pub fn push_segment(&mut self, segment: &[u8]) { - match &mut self.relative { - SubtreePathRelative::Empty => { - let mut bytes = CompactBytes::new(); - bytes.add_segment(segment); - self.relative = SubtreePathRelative::Multi(bytes); - } - SubtreePathRelative::Single(old_segment) => { - let mut bytes = CompactBytes::new(); - bytes.add_segment(old_segment); - bytes.add_segment(segment); - self.relative = SubtreePathRelative::Multi(bytes); - } - SubtreePathRelative::Multi(bytes) => bytes.add_segment(segment), - } - } - /// Returns an iterator for the subtree path by path segments. pub fn reverse_iter(&'b self) -> SubtreePathIter<'b, B> { match &self.relative { diff --git a/path/src/util/compact_bytes.rs b/path/src/util/compact_bytes.rs index 1e4362cb5..d4cdba9d0 100644 --- a/path/src/util/compact_bytes.rs +++ b/path/src/util/compact_bytes.rs @@ -31,7 +31,7 @@ use std::mem; /// Bytes vector wrapper to have multiple byte arrays allocated continuosuly. -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone)] pub(crate) struct CompactBytes { n_segments: usize, data: Vec, @@ -64,6 +64,29 @@ impl CompactBytes { pub fn len(&self) -> usize { self.n_segments } + + pub fn pop_segment(&mut self) -> Option> { + if self.n_segments < 1 { + return None; + } + + let length_size = mem::size_of::(); + let last_segment_length = usize::from_ne_bytes( + self.data[self.data.len() - length_size..] + .try_into() + .expect("internal structure bug"), + ); + + let segment = self.data + [self.data.len() - last_segment_length - length_size..self.data.len() - length_size] + .to_vec(); + + self.data + .truncate(self.data.len() - last_segment_length - length_size); + self.n_segments -= 1; + + Some(segment) + } } #[derive(Debug, Clone)] @@ -160,4 +183,25 @@ mod tests { assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } + + #[test] + fn pop_segment() { + let mut bytes = CompactBytes::default(); + bytes.add_segment(b"ayya"); + bytes.add_segment(b"ayyb"); + bytes.add_segment(b"ayyc"); + bytes.add_segment(b"ayyd"); + + assert_eq!(bytes.pop_segment(), Some(b"ayyd".to_vec())); + assert_eq!(bytes.pop_segment(), Some(b"ayyc".to_vec())); + + let mut v: Vec<_> = bytes.reverse_iter().collect(); + v.reverse(); + assert_eq!(v, vec![b"ayya".to_vec(), b"ayyb".to_vec()]); + + assert_eq!(bytes.pop_segment(), Some(b"ayyb".to_vec())); + assert_eq!(bytes.pop_segment(), Some(b"ayya".to_vec())); + assert_eq!(bytes.pop_segment(), None); + assert_eq!(bytes.pop_segment(), None); + } } diff --git a/path/src/util/cow_like.rs b/path/src/util/cow_like.rs index 78608ec89..02a535372 100644 --- a/path/src/util/cow_like.rs +++ b/path/src/util/cow_like.rs @@ -35,7 +35,7 @@ use std::{ /// A smart pointer that follows the semantics of [Cow](std::borrow::Cow) except /// provides no means for mutability and thus doesn't require [Clone]. -#[derive(Debug)] +#[derive(Debug, Clone)] pub enum CowLike<'b> { Owned(Vec), Borrowed(&'b [u8]), diff --git a/storage/src/rocksdb_storage.rs b/storage/src/rocksdb_storage.rs index 14c4df5ac..2905adce0 100644 --- a/storage/src/rocksdb_storage.rs +++ b/storage/src/rocksdb_storage.rs @@ -36,7 +36,7 @@ mod tests; pub use rocksdb::{Error, WriteBatchWithTransaction}; pub use storage_context::{ PrefixedRocksDbBatch, PrefixedRocksDbImmediateStorageContext, PrefixedRocksDbRawIterator, - PrefixedRocksDbStorageContext, PrefixedRocksDbTransactionContext, + PrefixedRocksDbTransactionContext, }; pub use self::storage::RocksDbStorage; diff --git a/storage/src/rocksdb_storage/storage.rs b/storage/src/rocksdb_storage/storage.rs index 8a91d4f47..7cedf49dc 100644 --- a/storage/src/rocksdb_storage/storage.rs +++ b/storage/src/rocksdb_storage/storage.rs @@ -44,10 +44,7 @@ use rocksdb::{ Transaction, WriteBatchWithTransaction, DEFAULT_COLUMN_FAMILY_NAME, }; -use super::{ - PrefixedRocksDbImmediateStorageContext, PrefixedRocksDbStorageContext, - PrefixedRocksDbTransactionContext, -}; +use super::{PrefixedRocksDbImmediateStorageContext, PrefixedRocksDbTransactionContext}; use crate::{ error, error::Error::{CostError, RocksDBError}, @@ -191,7 +188,7 @@ impl RocksDbStorage { db_batch.put(&key, &value); cost.seek_count += 1; cost_return_on_error_no_add!( - &cost, + cost, pending_costs .add_key_value_storage_costs( key.len() as u32, @@ -210,7 +207,7 @@ impl RocksDbStorage { db_batch.put_cf(cf_aux(&self.db), &key, &value); cost.seek_count += 1; cost_return_on_error_no_add!( - &cost, + cost, pending_costs .add_key_value_storage_costs( key.len() as u32, @@ -231,7 +228,7 @@ impl RocksDbStorage { // We only add costs for put root if they are set, otherwise it is free if cost_info.is_some() { cost_return_on_error_no_add!( - &cost, + cost, pending_costs .add_key_value_storage_costs( key.len() as u32, @@ -251,7 +248,7 @@ impl RocksDbStorage { db_batch.put_cf(cf_meta(&self.db), &key, &value); cost.seek_count += 1; cost_return_on_error_no_add!( - &cost, + cost, pending_costs .add_key_value_storage_costs( key.len() as u32, @@ -275,7 +272,7 @@ impl RocksDbStorage { cost.seek_count += 2; // lets get the values let value_len = cost_return_on_error_no_add!( - &cost, + cost, self.db.get(&key).map_err(RocksDBError) ) .map(|x| x.len() as u32) @@ -302,7 +299,7 @@ impl RocksDbStorage { } else { cost.seek_count += 2; let value_len = cost_return_on_error_no_add!( - &cost, + cost, self.db.get_cf(cf_aux(&self.db), &key).map_err(RocksDBError) ) .map(|x| x.len() as u32) @@ -330,7 +327,7 @@ impl RocksDbStorage { } else { cost.seek_count += 2; let value_len = cost_return_on_error_no_add!( - &cost, + cost, self.db .get_cf(cf_roots(&self.db), &key) .map_err(RocksDBError) @@ -360,7 +357,7 @@ impl RocksDbStorage { } else { cost.seek_count += 2; let value_len = cost_return_on_error_no_add!( - &cost, + cost, self.db .get_cf(cf_meta(&self.db), &key) .map_err(RocksDBError) @@ -435,7 +432,6 @@ impl RocksDbStorage { } impl<'db> Storage<'db> for RocksDbStorage { - type BatchStorageContext = PrefixedRocksDbStorageContext<'db>; type BatchTransactionalStorageContext = PrefixedRocksDbTransactionContext<'db>; type ImmediateStorageContext = PrefixedRocksDbImmediateStorageContext<'db>; type Transaction = Tx<'db>; @@ -460,18 +456,6 @@ impl<'db> Storage<'db> for RocksDbStorage { self.db.flush().map_err(RocksDBError) } - fn get_storage_context<'b, B>( - &'db self, - path: SubtreePath<'b, B>, - batch: Option<&'db StorageBatch>, - ) -> CostContext - where - B: AsRef<[u8]> + 'b, - { - Self::build_prefix(path) - .map(|prefix| PrefixedRocksDbStorageContext::new(&self.db, prefix, batch)) - } - fn get_transactional_storage_context<'b, B>( &'db self, path: SubtreePath<'b, B>, @@ -594,11 +578,12 @@ mod tests { }; let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let left = storage - .get_storage_context(left_path.clone(), Some(&batch)) + .get_transactional_storage_context(left_path.clone(), Some(&batch), &tx) .unwrap(); let right = storage - .get_storage_context(right_path.clone(), Some(&batch)) + .get_transactional_storage_context(right_path.clone(), Some(&batch), &tx) .unwrap(); left.put(b"a", b"a", None, None).unwrap().unwrap(); @@ -615,11 +600,12 @@ mod tests { .expect("cannot commit batch"); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let left = storage - .get_storage_context(left_path.clone(), Some(&batch)) + .get_transactional_storage_context(left_path.clone(), Some(&batch), &tx) .unwrap(); let right = storage - .get_storage_context(right_path.clone(), Some(&batch)) + .get_transactional_storage_context(right_path.clone(), Some(&batch), &tx) .unwrap(); // Iterate over left subtree while right subtree contains 1 byte keys: @@ -660,7 +646,10 @@ mod tests { .unwrap() .expect("cannot commit batch"); - let left = storage.get_storage_context(left_path, None).unwrap(); + let tx = storage.start_transaction(); + let left = storage + .get_transactional_storage_context(left_path, None, &tx) + .unwrap(); // Iterate over left subtree once again let mut iteration_cost_after = OperationCost::default(); let mut iter = left.raw_iter(); diff --git a/storage/src/rocksdb_storage/storage_context.rs b/storage/src/rocksdb_storage/storage_context.rs index 0611d51c1..758ba16fb 100644 --- a/storage/src/rocksdb_storage/storage_context.rs +++ b/storage/src/rocksdb_storage/storage_context.rs @@ -30,13 +30,11 @@ mod batch; pub mod context_immediate; -mod context_no_tx; mod context_tx; mod raw_iterator; pub use batch::PrefixedRocksDbBatch; pub use context_immediate::PrefixedRocksDbImmediateStorageContext; -pub use context_no_tx::PrefixedRocksDbStorageContext; pub use context_tx::PrefixedRocksDbTransactionContext; pub use raw_iterator::PrefixedRocksDbRawIterator; diff --git a/storage/src/rocksdb_storage/storage_context/context_no_tx.rs b/storage/src/rocksdb_storage/storage_context/context_no_tx.rs deleted file mode 100644 index 80ad01499..000000000 --- a/storage/src/rocksdb_storage/storage_context/context_no_tx.rs +++ /dev/null @@ -1,286 +0,0 @@ -// MIT LICENSE -// -// Copyright (c) 2021 Dash Core Group -// -// Permission is hereby granted, free of charge, to any -// person obtaining a copy of this software and associated -// documentation files (the "Software"), to deal in the -// Software without restriction, including without -// limitation the rights to use, copy, modify, merge, -// publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software -// is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice -// shall be included in all copies or substantial portions -// of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -//! Storage context batch implementation without a transaction - -use error::Error; -use grovedb_costs::{ - storage_cost::key_value_cost::KeyValueStorageCost, ChildrenSizesWithIsSumTree, CostResult, - CostsExt, OperationCost, -}; -use rocksdb::{ColumnFamily, DBRawIteratorWithThreadMode}; - -use super::{batch::PrefixedMultiContextBatchPart, make_prefixed_key, PrefixedRocksDbRawIterator}; -use crate::{ - error, - error::Error::RocksDBError, - rocksdb_storage::storage::{Db, SubtreePrefix, AUX_CF_NAME, META_CF_NAME, ROOTS_CF_NAME}, - StorageBatch, StorageContext, -}; - -/// Storage context with a prefix applied to be used in a subtree to be used -/// outside of transaction. -pub struct PrefixedRocksDbStorageContext<'db> { - storage: &'db Db, - prefix: SubtreePrefix, - batch: Option<&'db StorageBatch>, -} - -impl<'db> PrefixedRocksDbStorageContext<'db> { - /// Create a new prefixed storage_cost context instance - pub fn new(storage: &'db Db, prefix: SubtreePrefix, batch: Option<&'db StorageBatch>) -> Self { - PrefixedRocksDbStorageContext { - storage, - prefix, - batch, - } - } -} - -impl<'db> PrefixedRocksDbStorageContext<'db> { - /// Get auxiliary data column family - fn cf_aux(&self) -> &'db ColumnFamily { - self.storage - .cf_handle(AUX_CF_NAME) - .expect("aux column family must exist") - } - - /// Get trees roots data column family - fn cf_roots(&self) -> &'db ColumnFamily { - self.storage - .cf_handle(ROOTS_CF_NAME) - .expect("roots column family must exist") - } - - /// Get metadata column family - fn cf_meta(&self) -> &'db ColumnFamily { - self.storage - .cf_handle(META_CF_NAME) - .expect("meta column family must exist") - } -} - -impl<'db> StorageContext<'db> for PrefixedRocksDbStorageContext<'db> { - type Batch = PrefixedMultiContextBatchPart; - type RawIterator = PrefixedRocksDbRawIterator>; - - fn put>( - &self, - key: K, - value: &[u8], - children_sizes: ChildrenSizesWithIsSumTree, - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.put( - make_prefixed_key(&self.prefix, key), - value.to_vec(), - children_sizes, - cost_info, - ); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn put_aux>( - &self, - key: K, - value: &[u8], - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.put_aux( - make_prefixed_key(&self.prefix, key), - value.to_vec(), - cost_info, - ); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn put_root>( - &self, - key: K, - value: &[u8], - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.put_root( - make_prefixed_key(&self.prefix, key), - value.to_vec(), - cost_info, - ); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn put_meta>( - &self, - key: K, - value: &[u8], - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.put_meta( - make_prefixed_key(&self.prefix, key), - value.to_vec(), - cost_info, - ); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn delete>( - &self, - key: K, - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.delete(make_prefixed_key(&self.prefix, key), cost_info); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn delete_aux>( - &self, - key: K, - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.delete_aux(make_prefixed_key(&self.prefix, key), cost_info); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn delete_root>( - &self, - key: K, - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.delete_root(make_prefixed_key(&self.prefix, key), cost_info); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn delete_meta>( - &self, - key: K, - cost_info: Option, - ) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.delete_meta(make_prefixed_key(&self.prefix, key), cost_info); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn get>(&self, key: K) -> CostResult>, Error> { - self.storage - .get(make_prefixed_key(&self.prefix, key)) - .map_err(RocksDBError) - .wrap_fn_cost(|value| OperationCost { - seek_count: 1, - storage_loaded_bytes: value - .as_ref() - .ok() - .and_then(Option::as_ref) - .map(|x| x.len() as u64) - .unwrap_or(0), - ..Default::default() - }) - } - - fn get_aux>(&self, key: K) -> CostResult>, Error> { - self.storage - .get_cf(self.cf_aux(), make_prefixed_key(&self.prefix, key)) - .map_err(RocksDBError) - .wrap_fn_cost(|value| OperationCost { - seek_count: 1, - storage_loaded_bytes: value - .as_ref() - .ok() - .and_then(Option::as_ref) - .map(|x| x.len() as u64) - .unwrap_or(0), - ..Default::default() - }) - } - - fn get_root>(&self, key: K) -> CostResult>, Error> { - self.storage - .get_cf(self.cf_roots(), make_prefixed_key(&self.prefix, key)) - .map_err(RocksDBError) - .wrap_fn_cost(|value| OperationCost { - seek_count: 1, - storage_loaded_bytes: value - .as_ref() - .ok() - .and_then(Option::as_ref) - .map(|x| x.len() as u64) - .unwrap_or(0), - ..Default::default() - }) - } - - fn get_meta>(&self, key: K) -> CostResult>, Error> { - self.storage - .get_cf(self.cf_meta(), make_prefixed_key(&self.prefix, key)) - .map_err(RocksDBError) - .wrap_fn_cost(|value| OperationCost { - seek_count: 1, - storage_loaded_bytes: value - .as_ref() - .ok() - .and_then(Option::as_ref) - .map(|x| x.len() as u64) - .unwrap_or(0), - ..Default::default() - }) - } - - fn new_batch(&self) -> Self::Batch { - PrefixedMultiContextBatchPart { - prefix: self.prefix, - batch: StorageBatch::new(), - } - } - - fn commit_batch(&self, batch: Self::Batch) -> CostResult<(), Error> { - if let Some(existing_batch) = self.batch { - existing_batch.merge(batch.batch); - } - Ok(()).wrap_with_cost(OperationCost::default()) - } - - fn raw_iter(&self) -> Self::RawIterator { - PrefixedRocksDbRawIterator { - prefix: self.prefix, - raw_iterator: self.storage.raw_iterator(), - } - } -} diff --git a/storage/src/rocksdb_storage/tests.rs b/storage/src/rocksdb_storage/tests.rs index c75568cd5..4000be366 100644 --- a/storage/src/rocksdb_storage/tests.rs +++ b/storage/src/rocksdb_storage/tests.rs @@ -555,11 +555,12 @@ mod batch_no_transaction { fn test_various_cf_methods() { let storage = TempStorage::new(); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayya"].as_ref().into(), Some(&batch), &tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), Some(&batch), &tx) .unwrap(); context_ayya @@ -611,10 +612,10 @@ mod batch_no_transaction { .expect("cannot commit batch"); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), None) + .get_transactional_storage_context([b"ayya"].as_ref().into(), None, &tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), None) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), None, &tx) .unwrap(); assert_eq!( @@ -696,11 +697,12 @@ mod batch_no_transaction { fn test_with_db_batches() { let storage = TempStorage::new(); let batch = StorageBatch::new(); + let tx = storage.start_transaction(); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayya"].as_ref().into(), Some(&batch), &tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), Some(&batch), &tx) .unwrap(); context_ayya @@ -761,7 +763,7 @@ mod batch_no_transaction { .expect("cannot commit multi context batch"); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), None) + .get_transactional_storage_context([b"ayya"].as_ref().into(), None, &tx) .unwrap(); assert_eq!( context_ayya @@ -786,11 +788,13 @@ mod batch_transaction { let batch = StorageBatch::new(); let batch_tx = StorageBatch::new(); + + let other_tx = storage.start_transaction(); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayya"].as_ref().into(), Some(&batch), &other_tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), Some(&batch)) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), Some(&batch), &other_tx) .unwrap(); let context_ayya_tx = storage .get_transactional_storage_context( @@ -1033,11 +1037,12 @@ mod batch_transaction { ); // And still no data in the database until transaction is commited + let other_tx = storage.start_transaction(); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), None) + .get_transactional_storage_context([b"ayya"].as_ref().into(), None, &other_tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), None) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), None, &other_tx) .unwrap(); let mut iter = context_ayya.raw_iter(); @@ -1053,11 +1058,12 @@ mod batch_transaction { .unwrap() .expect("cannot commit transaction"); + let other_tx = storage.start_transaction(); let context_ayya = storage - .get_storage_context([b"ayya"].as_ref().into(), None) + .get_transactional_storage_context([b"ayya"].as_ref().into(), None, &other_tx) .unwrap(); let context_ayyb = storage - .get_storage_context([b"ayyb"].as_ref().into(), None) + .get_transactional_storage_context([b"ayyb"].as_ref().into(), None, &other_tx) .unwrap(); assert_eq!( diff --git a/storage/src/storage.rs b/storage/src/storage.rs index 5ef26e064..3a0b54852 100644 --- a/storage/src/storage.rs +++ b/storage/src/storage.rs @@ -43,16 +43,13 @@ use grovedb_visualize::visualize_to_vec; use crate::{worst_case_costs::WorstKeyLength, Error}; -/// Top-level storage_cost abstraction. -/// Should be able to hold storage_cost connection and to start transaction when +/// Top-level storage abstraction. +/// Should be able to hold storage connection and to start transaction when /// needed. All query operations will be exposed using [StorageContext]. pub trait Storage<'db> { /// Storage transaction type type Transaction; - /// Storage context type for mutli-tree batch operations - type BatchStorageContext: StorageContext<'db>; - /// Storage context type for multi-tree batch operations inside transaction type BatchTransactionalStorageContext: StorageContext<'db>; @@ -79,16 +76,6 @@ pub trait Storage<'db> { /// Forces data to be written fn flush(&self) -> Result<(), Error>; - /// Make storage context for a subtree with path, keeping all write - /// operations inside a `batch` if provided. - fn get_storage_context<'b, B>( - &'db self, - path: SubtreePath<'b, B>, - batch: Option<&'db StorageBatch>, - ) -> CostContext - where - B: AsRef<[u8]> + 'b; - /// Make context for a subtree on transactional data, keeping all write /// operations inside a `batch` if provided. fn get_transactional_storage_context<'b, B>( @@ -113,7 +100,7 @@ pub trait Storage<'db> { /// Creates a database checkpoint in a specified path fn create_checkpoint>(&self, path: P) -> Result<(), Error>; - /// Return worst case cost for storage_cost context creation. + /// Return worst case cost for storage context creation. fn get_storage_context_cost(path: &[L]) -> OperationCost; } @@ -126,11 +113,11 @@ pub trait StorageContext<'db> { /// Storage batch type type Batch: Batch; - /// Storage raw iterator type (to iterate over storage_cost without + /// Storage raw iterator type (to iterate over storage without /// supplying a key) type RawIterator: RawIterator; - /// Put `value` into data storage_cost with `key` + /// Put `value` into data storage with `key` fn put>( &self, key: K, @@ -139,7 +126,7 @@ pub trait StorageContext<'db> { cost_info: Option, ) -> CostResult<(), Error>; - /// Put `value` into auxiliary data storage_cost with `key` + /// Put `value` into auxiliary data storage with `key` fn put_aux>( &self, key: K, @@ -147,7 +134,7 @@ pub trait StorageContext<'db> { cost_info: Option, ) -> CostResult<(), Error>; - /// Put `value` into trees roots storage_cost with `key` + /// Put `value` into trees roots storage with `key` fn put_root>( &self, key: K, @@ -155,7 +142,7 @@ pub trait StorageContext<'db> { cost_info: Option, ) -> CostResult<(), Error>; - /// Put `value` into GroveDB metadata storage_cost with `key` + /// Put `value` into GroveDB metadata storage with `key` fn put_meta>( &self, key: K, @@ -163,44 +150,44 @@ pub trait StorageContext<'db> { cost_info: Option, ) -> CostResult<(), Error>; - /// Delete entry with `key` from data storage_cost + /// Delete entry with `key` from data storage fn delete>( &self, key: K, cost_info: Option, ) -> CostResult<(), Error>; - /// Delete entry with `key` from auxiliary data storage_cost + /// Delete entry with `key` from auxiliary data storage fn delete_aux>( &self, key: K, cost_info: Option, ) -> CostResult<(), Error>; - /// Delete entry with `key` from trees roots storage_cost + /// Delete entry with `key` from trees roots storage fn delete_root>( &self, key: K, cost_info: Option, ) -> CostResult<(), Error>; - /// Delete entry with `key` from GroveDB metadata storage_cost + /// Delete entry with `key` from GroveDB metadata storage fn delete_meta>( &self, key: K, cost_info: Option, ) -> CostResult<(), Error>; - /// Get entry by `key` from data storage_cost + /// Get entry by `key` from data storage fn get>(&self, key: K) -> CostResult>, Error>; - /// Get entry by `key` from auxiliary data storage_cost + /// Get entry by `key` from auxiliary data storage fn get_aux>(&self, key: K) -> CostResult>, Error>; - /// Get entry by `key` from trees roots storage_cost + /// Get entry by `key` from trees roots storage fn get_root>(&self, key: K) -> CostResult>, Error>; - /// Get entry by `key` from GroveDB metadata storage_cost + /// Get entry by `key` from GroveDB metadata storage fn get_meta>(&self, key: K) -> CostResult>, Error>; /// Initialize a new batch @@ -209,7 +196,7 @@ pub trait StorageContext<'db> { /// Commits changes from batch into storage fn commit_batch(&self, batch: Self::Batch) -> CostResult<(), Error>; - /// Get raw iterator over storage_cost + /// Get raw iterator over storage fn raw_iter(&self) -> Self::RawIterator; } @@ -224,7 +211,7 @@ pub trait Batch { cost_info: Option, ) -> Result<(), grovedb_costs::error::Error>; - /// Appends to the database batch a put operation for aux storage_cost. + /// Appends to the database batch a put operation for aux storage. fn put_aux>( &mut self, key: K, @@ -233,7 +220,7 @@ pub trait Batch { ) -> Result<(), grovedb_costs::error::Error>; /// Appends to the database batch a put operation for subtrees roots - /// storage_cost. + /// storage. fn put_root>( &mut self, key: K, @@ -244,15 +231,15 @@ pub trait Batch { /// Appends to the database batch a delete operation for a data record. fn delete>(&mut self, key: K, cost_info: Option); - /// Appends to the database batch a delete operation for aux storage_cost. + /// Appends to the database batch a delete operation for aux storage. fn delete_aux>(&mut self, key: K, cost_info: Option); /// Appends to the database batch a delete operation for a record in subtree - /// roots storage_cost. + /// roots storage. fn delete_root>(&mut self, key: K, cost_info: Option); } -/// Allows to iterate over database record inside of storage_cost context. +/// Allows to iterate over database record inside of storage context. pub trait RawIterator { /// Move iterator to first valid record. fn seek_to_first(&mut self) -> CostContext<()>; @@ -282,7 +269,7 @@ pub trait RawIterator { fn valid(&self) -> CostContext; } -/// Structure to hold deferred database operations in "batched" storage_cost +/// Structure to hold deferred database operations in "batched" storage /// contexts. #[derive(Debug)] pub struct StorageBatch { @@ -318,8 +305,8 @@ impl StorageBatch { } } - #[cfg(test)] - pub(crate) fn len(&self) -> usize { + /// Returns a number of operations in the batch. + pub fn len(&self) -> usize { let operations = self.operations.borrow(); operations.data.len() + operations.roots.len() @@ -346,7 +333,7 @@ impl StorageBatch { ); } - /// Add deferred `put` operation for aux storage_cost + /// Add deferred `put` operation for aux storage pub(crate) fn put_aux( &self, key: Vec, @@ -363,7 +350,7 @@ impl StorageBatch { ); } - /// Add deferred `put` operation for subtree roots storage_cost + /// Add deferred `put` operation for subtree roots storage pub(crate) fn put_root( &self, key: Vec, @@ -380,7 +367,7 @@ impl StorageBatch { ); } - /// Add deferred `put` operation for metadata storage_cost + /// Add deferred `put` operation for metadata storage pub(crate) fn put_meta( &self, key: Vec, @@ -408,7 +395,7 @@ impl StorageBatch { } } - /// Add deferred `delete` operation for aux storage_cost + /// Add deferred `delete` operation for aux storage pub(crate) fn delete_aux(&self, key: Vec, cost_info: Option) { let operations = &mut self.operations.borrow_mut().aux; if operations.get(&key).is_none() { @@ -419,7 +406,7 @@ impl StorageBatch { } } - /// Add deferred `delete` operation for subtree roots storage_cost + /// Add deferred `delete` operation for subtree roots storage pub(crate) fn delete_root(&self, key: Vec, cost_info: Option) { let operations = &mut self.operations.borrow_mut().roots; if operations.get(&key).is_none() { @@ -430,7 +417,7 @@ impl StorageBatch { } } - /// Add deferred `delete` operation for metadata storage_cost + /// Add deferred `delete` operation for metadata storage pub(crate) fn delete_meta(&self, key: Vec, cost_info: Option) { let operations = &mut self.operations.borrow_mut().meta; if operations.get(&key).is_none() { @@ -481,7 +468,7 @@ impl StorageBatch { } } -/// Iterator over storage_cost batch operations. +/// Iterator over storage batch operations. pub(crate) struct StorageBatchIter { data: IntoValues, AbstractBatchOperation>, aux: IntoValues, AbstractBatchOperation>, @@ -522,7 +509,7 @@ impl Default for StorageBatch { } } -/// Deferred storage_cost operation not tied to any storage_cost implementation, +/// Deferred storage operation not tied to any storage implementation, /// required for multi-tree batches. #[allow(missing_docs)] #[derive(strum::AsRefStr)] @@ -534,19 +521,19 @@ pub(crate) enum AbstractBatchOperation { children_sizes: ChildrenSizesWithIsSumTree, cost_info: Option, }, - /// Deferred put operation for aux storage_cost + /// Deferred put operation for aux storage PutAux { key: Vec, value: Vec, cost_info: Option, }, - /// Deferred put operation for roots storage_cost + /// Deferred put operation for roots storage PutRoot { key: Vec, value: Vec, cost_info: Option, }, - /// Deferred put operation for metadata storage_cost + /// Deferred put operation for metadata storage PutMeta { key: Vec, value: Vec, @@ -557,17 +544,17 @@ pub(crate) enum AbstractBatchOperation { key: Vec, cost_info: Option, }, - /// Deferred delete operation for aux storage_cost + /// Deferred delete operation for aux storage DeleteAux { key: Vec, cost_info: Option, }, - /// Deferred delete operation for roots storage_cost + /// Deferred delete operation for roots storage DeleteRoot { key: Vec, cost_info: Option, }, - /// Deferred delete operation for metadata storage_cost + /// Deferred delete operation for metadata storage DeleteMeta { key: Vec, cost_info: Option, From f7d41053a40032692ef16c3c20e77c8e6f97485a Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 14:02:26 +0100 Subject: [PATCH 2/9] add version for delta functions --- grovedb-version/src/version/grovedb_versions.rs | 2 ++ grovedb-version/src/version/v1.rs | 2 ++ grovedb/src/element/insert.rs | 14 ++++++++++---- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/grovedb-version/src/version/grovedb_versions.rs b/grovedb-version/src/version/grovedb_versions.rs index cc52e6199..81790384e 100644 --- a/grovedb-version/src/version/grovedb_versions.rs +++ b/grovedb-version/src/version/grovedb_versions.rs @@ -204,8 +204,10 @@ pub struct GroveDBElementMethodVersions { pub insert_if_changed_value: FeatureVersion, pub insert_if_changed_value_into_batch_operations: FeatureVersion, pub insert_reference: FeatureVersion, + pub insert_reference_if_changed_value: FeatureVersion, pub insert_reference_into_batch_operations: FeatureVersion, pub insert_subtree: FeatureVersion, + pub insert_subtree_if_changed: FeatureVersion, pub insert_subtree_into_batch_operations: FeatureVersion, pub get_query: FeatureVersion, pub get_query_values: FeatureVersion, diff --git a/grovedb-version/src/version/v1.rs b/grovedb-version/src/version/v1.rs index b6245e561..7dc1ccbb7 100644 --- a/grovedb-version/src/version/v1.rs +++ b/grovedb-version/src/version/v1.rs @@ -52,8 +52,10 @@ pub const GROVE_V1: GroveVersion = GroveVersion { insert_if_changed_value: 0, insert_if_changed_value_into_batch_operations: 0, insert_reference: 0, + insert_reference_if_changed_value: 0, insert_reference_into_batch_operations: 0, insert_subtree: 0, + insert_subtree_if_changed: 0, insert_subtree_into_batch_operations: 0, get_query: 0, get_query_values: 0, diff --git a/grovedb/src/element/insert.rs b/grovedb/src/element/insert.rs index 9f75e1d2f..5d1927283 100644 --- a/grovedb/src/element/insert.rs +++ b/grovedb/src/element/insert.rs @@ -341,8 +341,11 @@ impl Element { grove_version: &GroveVersion, ) -> CostResult { check_grovedb_v0_with_cost!( - "insert_reference", - grove_version.grovedb_versions.element.insert_reference + "insert_reference_if_changed_value", + grove_version + .grovedb_versions + .element + .insert_reference_if_changed_value ); let serialized = match self.serialize(grove_version) { @@ -492,8 +495,11 @@ impl Element { grove_version: &GroveVersion, ) -> CostResult { check_grovedb_v0_with_cost!( - "insert_subtree", - grove_version.grovedb_versions.element.insert_subtree + "insert_subtree_if_changed", + grove_version + .grovedb_versions + .element + .insert_subtree_if_changed ); let serialized = match self.serialize(grove_version) { From a771e6ae3787792203d5edb0eb2766ef16582364 Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 14:13:26 +0100 Subject: [PATCH 3/9] remove obsolete code --- grovedb/src/util.rs | 65 --------------------------------------------- 1 file changed, 65 deletions(-) diff --git a/grovedb/src/util.rs b/grovedb/src/util.rs index 70db057c0..321cd5265 100644 --- a/grovedb/src/util.rs +++ b/grovedb/src/util.rs @@ -114,40 +114,6 @@ where } } -// /// Wrapper type that keeps path and key used to perform an operation. -// pub(crate) struct WithOrigin<'b, 'k, B, T> { -// pub(crate) path: SubtreePath<'b, B>, -// pub(crate) key: &'k [u8], -// pub(crate) value: T, -// } - -// impl<'b, 'k, B, T> WithOrigin<'b, 'k, B, T> { -// pub(crate) fn run( -// path: SubtreePath<'b, B>, -// key: &'k [u8], -// f: impl FnOnce(SubtreePath<'b, B>, &'k [u8]) -> T, -// ) -> Self { -// WithOrigin { -// path: path.clone(), -// key, -// value: f(path, key), -// } -// } -// } - -// impl<'b, 'k, B, T, E> WithOrigin<'b, 'k, B, CostResult> { -// pub(crate) fn into_cost_result(self) -> CostResult, E> { let mut cost = Default::default(); -// let value = cost_return_on_error!(&mut cost, self.value); -// Ok(WithOrigin { -// value, -// path: self.path, -// key: self.key, -// }) -// .wrap_with_cost(cost) -// } -// } - pub(crate) struct ResolvedReference<'db, 'b, 'c, B> { pub target_merk: MerkHandle<'db, 'c>, pub target_path: SubtreePathBuilder<'b, B>, @@ -292,34 +258,3 @@ pub(crate) fn follow_reference_once<'db, 'b, 'c, B: AsRef<[u8]>>( }) .wrap_with_cost(cost) } - -// #[cfg(test)] -// mod tests { -// use pretty_assertions::assert_eq; - -// use super::*; -// use crate::tests::{make_deep_tree, TEST_LEAF}; - -// #[test] -// fn with_origin() { -// let version = GroveVersion::latest(); -// let db = make_deep_tree(&version); - -// let wo = WithOrigin::run( -// SubtreePath::from(&[TEST_LEAF, b"innertree"]), -// b"key1", -// |path, key| db.get(path, key, None, &version), -// ); - -// assert_eq!(wo.path, SubtreePath::from(&[TEST_LEAF, b"innertree"])); -// assert_eq!(wo.key, b"key1"); - -// let with_origin_cost_result: CostResult<_, _> = -// wo.into_cost_result(); - -// assert_eq!( -// with_origin_cost_result.unwrap().unwrap().value, -// Element::Item(b"value1".to_vec(), None) -// ); -// } -// } From bcdfbbda9488876828c7fc34ecba623e4dd73cac Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 14:22:51 +0100 Subject: [PATCH 4/9] fix misleading comment --- path/src/subtree_path_builder.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/path/src/subtree_path_builder.rs b/path/src/subtree_path_builder.rs index 6ac779775..f3a7d5538 100644 --- a/path/src/subtree_path_builder.rs +++ b/path/src/subtree_path_builder.rs @@ -240,9 +240,9 @@ impl<'b, B: AsRef<[u8]>> SubtreePathBuilder<'b, B> { } } - /// Get a derived path for a parent and a chopped segment. Returned - /// [SubtreePath] will be linked to this [SubtreePath] because it might - /// contain owned data and it has to outlive [SubtreePath]. + /// Get a derived path for a parent and a chopped segment. The lifetime of returned path is + /// constrained solely by the original slice that this whole path hierarchy is based upon, and the point + /// of derivation has no effect on it. pub fn derive_parent_owned(&self) -> Option<(SubtreePathBuilder<'b, B>, Vec)> { match &self.relative { SubtreePathRelative::Empty => self From 107830715a616ea476da9de637f47a8268177840 Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 16:38:46 +0100 Subject: [PATCH 5/9] revert possible cost mismatch for reference insertion --- grovedb/src/operations/insert/mod.rs | 106 +++++++++++++++++++++------ grovedb/src/tests/mod.rs | 2 + 2 files changed, 84 insertions(+), 24 deletions(-) diff --git a/grovedb/src/operations/insert/mod.rs b/grovedb/src/operations/insert/mod.rs index 0c5f03e6e..6eb726ad4 100644 --- a/grovedb/src/operations/insert/mod.rs +++ b/grovedb/src/operations/insert/mod.rs @@ -12,8 +12,9 @@ use grovedb_version::{check_grovedb_v0_with_cost, version::GroveVersion}; use crate::{ merk_cache::{MerkCache, MerkHandle}, - util::{self, TxRef}, - Element, Error, GroveDb, TransactionArg, + reference_path::path_from_reference_path_type, + util::TxRef, + Element, Error, GroveDb, Transaction, TransactionArg, }; #[derive(Clone)] /// Insert options @@ -81,6 +82,7 @@ impl GroveDb { element, options.unwrap_or_default(), &merk_cache, + tx.as_ref(), grove_version ) ); @@ -106,6 +108,9 @@ impl GroveDb { element: Element, options: InsertOptions, merk_cache: &'c MerkCache<'db, 'b, B>, + // TODO: only required for costs compatiblity for references insertion, shall be split + // using versioning + transaction: &Transaction, grove_version: &GroveVersion, ) -> CostResult, Error> { check_grovedb_v0_with_cost!( @@ -163,35 +168,41 @@ impl GroveDb { match element { Element::Reference(ref reference_path, ..) => { - let resolved_reference = cost_return_on_error!( + // TODO: this is an old version used to maintain the same costs as before, + // however, using reference resolution over merk cache may optimize the process + // and total cost of it, but those improvements with `util::follow_reference` + // shall go to the next version of `insert` function + let path = path.to_vec(); + let reference_path = cost_return_on_error!( &mut cost, - util::follow_reference( - merk_cache, - path.derive_owned(), - key, - reference_path.clone() + path_from_reference_path_type(reference_path.clone(), &path, Some(key)) + .wrap_with_cost(OperationCost::default()) + ); + + let referenced_item = cost_return_on_error!( + &mut cost, + self.follow_reference( + reference_path.as_slice().into(), + false, + transaction, + grove_version ) ); - if matches!( - resolved_reference.target_element, - Element::Tree(_, _) | Element::SumTree(_, _, _) - ) { - return Err(Error::NotSupported( - "References cannot point to subtrees".to_owned(), - )) - .wrap_with_cost(cost); - } + let referenced_element_value_hash = + cost_return_on_error!(&mut cost, referenced_item.value_hash(grove_version)); cost_return_on_error!( &mut cost, - subtree_to_insert_into.for_merk(|m| element.insert_reference( - m, - key, - resolved_reference.target_node_value_hash, - Some(options.as_merk_options()), - grove_version, - )) + subtree_to_insert_into.for_merk(|m| { + element.insert_reference( + m, + key, + referenced_element_value_hash, + Some(options.as_merk_options()), + grove_version, + ) + }) ); } @@ -393,6 +404,7 @@ mod tests { use crate::{ operations::insert::InsertOptions, + reference_path::ReferencePathType, tests::{common::EMPTY_PATH, make_empty_grovedb, make_test_grovedb, TEST_LEAF}, Element, Error, }; @@ -1940,6 +1952,52 @@ mod tests { ); } + #[test] + fn test_reference_insertion_cost() { + let grove_version = GroveVersion::latest(); + let db = make_empty_grovedb(); + let tx = db.start_transaction(); + + db.insert( + EMPTY_PATH, + b"key1", + Element::new_item(b"value".to_vec()), + None, + Some(&tx), + grove_version, + ) + .unwrap() + .unwrap(); + + let cost = db + .insert( + EMPTY_PATH, + b"key2", + Element::new_reference(ReferencePathType::AbsolutePathReference(vec![ + b"key1".to_vec() + ])), + None, + Some(&tx), + grove_version, + ) + .cost_as_result() + .expect("expected to insert"); + + assert_eq!( + cost, + OperationCost { + seek_count: 8, // todo: verify this + storage_cost: StorageCost { + added_bytes: 153, + replaced_bytes: 114, // todo: verify this + removed_bytes: NoStorageRemoval + }, + storage_loaded_bytes: 233, + hash_node_calls: 6, + } + ); + } + #[test] fn test_one_update_tree_bigger_cost_with_flags() { let grove_version = GroveVersion::latest(); diff --git a/grovedb/src/tests/mod.rs b/grovedb/src/tests/mod.rs index 126e3654a..624b6abf9 100644 --- a/grovedb/src/tests/mod.rs +++ b/grovedb/src/tests/mod.rs @@ -4143,7 +4143,9 @@ mod tests { } } +// TODO: shall go to the next version #[test] +#[ignore] fn subtrees_cant_be_referenced() { let db = make_deep_tree(&GroveVersion::latest()); assert!(db From faeed027880f56ecda36b98c7681bbe5db225db5 Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 17:21:03 +0100 Subject: [PATCH 6/9] fix compilation issue --- grovedb/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/grovedb/src/lib.rs b/grovedb/src/lib.rs index b7741acf1..7885335e5 100644 --- a/grovedb/src/lib.rs +++ b/grovedb/src/lib.rs @@ -208,6 +208,7 @@ pub use query::{PathQuery, SizedQuery}; use reference_path::path_from_reference_path_type; #[cfg(feature = "grovedbg")] use tokio::net::ToSocketAddrs; +#[cfg(feature = "full")] use util::TxRef; #[cfg(feature = "full")] From 70e0aa9a55ca707d98b7d8951ad3d9f0db2c7f1d Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 18:02:48 +0100 Subject: [PATCH 7/9] address some clippy issues --- grovedb/src/operations/insert/mod.rs | 2 +- grovedb/src/reference_path.rs | 4 ++-- grovedb/src/util.rs | 2 +- merk/src/merk/meta.rs | 4 ++-- merk/src/merk/mod.rs | 2 +- path/src/subtree_path.rs | 18 +++++++++--------- path/src/subtree_path_builder.rs | 23 ++++++++++++----------- storage/src/storage.rs | 5 +++++ 8 files changed, 33 insertions(+), 27 deletions(-) diff --git a/grovedb/src/operations/insert/mod.rs b/grovedb/src/operations/insert/mod.rs index 6eb726ad4..23582e3de 100644 --- a/grovedb/src/operations/insert/mod.rs +++ b/grovedb/src/operations/insert/mod.rs @@ -72,7 +72,7 @@ impl GroveDb { let tx = TxRef::new(&self.db, transaction); let mut cost = OperationCost::default(); - let merk_cache = MerkCache::new(&self, tx.as_ref(), grove_version); + let merk_cache = MerkCache::new(self, tx.as_ref(), grove_version); cost_return_on_error!( &mut cost, diff --git a/grovedb/src/reference_path.rs b/grovedb/src/reference_path.rs index a5e54f956..6af429c3d 100644 --- a/grovedb/src/reference_path.rs +++ b/grovedb/src/reference_path.rs @@ -137,9 +137,9 @@ fn display_path(path: &[Vec]) -> String { .map(|bytes| { let mut hx = hex::encode(bytes); if let Ok(s) = String::from_utf8(bytes.clone()) { - hx.push_str("("); + hx.push('('); hx.push_str(&s); - hx.push_str(")"); + hx.push(')'); } hx diff --git a/grovedb/src/util.rs b/grovedb/src/util.rs index 321cd5265..b6a1a2676 100644 --- a/grovedb/src/util.rs +++ b/grovedb/src/util.rs @@ -44,7 +44,7 @@ impl<'a, 'db> TxRef<'a, 'db> { } } -impl<'a, 'db> AsRef> for TxRef<'a, 'db> { +impl<'db> AsRef> for TxRef<'_, 'db> { fn as_ref(&self) -> &Transaction<'db> { match self { TxRef::Owned(tx) => tx, diff --git a/merk/src/merk/meta.rs b/merk/src/merk/meta.rs index e967dfd23..a51b7acff 100644 --- a/merk/src/merk/meta.rs +++ b/merk/src/merk/meta.rs @@ -10,7 +10,7 @@ use crate::Error; impl<'db, S: StorageContext<'db>> Merk { /// Get metadata for the Merk under `key`. - pub fn get_meta<'s>(&'s mut self, key: Vec) -> CostResult, Error> { + pub fn get_meta(&mut self, key: Vec) -> CostResult, Error> { match self.meta_cache.entry(key) { Entry::Occupied(e) => Ok(e.into_mut().as_deref()).wrap_with_cost(Default::default()), Entry::Vacant(e) => self @@ -34,7 +34,7 @@ impl<'db, S: StorageContext<'db>> Merk { /// Delete metadata under `key`. pub fn delete_meta(&mut self, key: &[u8]) -> CostResult<(), Error> { self.storage - .delete_meta(&key, None) + .delete_meta(key, None) .map_ok(|_| { self.meta_cache.remove(key); }) diff --git a/merk/src/merk/mod.rs b/merk/src/merk/mod.rs index b5d9e01ba..bc28f4602 100644 --- a/merk/src/merk/mod.rs +++ b/merk/src/merk/mod.rs @@ -189,7 +189,7 @@ impl<'a, I: RawIterator> KVIterator<'a, I> { } // Cannot be an Iterator as it should return cost -impl<'a, I: RawIterator> KVIterator<'a, I> { +impl KVIterator<'_, I> { /// Next key-value pub fn next_kv(&mut self) -> CostContext, Vec)>> { let mut cost = OperationCost::default(); diff --git a/path/src/subtree_path.rs b/path/src/subtree_path.rs index b754b91ed..48929a174 100644 --- a/path/src/subtree_path.rs +++ b/path/src/subtree_path.rs @@ -52,7 +52,7 @@ pub struct SubtreePath<'b, B> { pub(crate) ref_variant: SubtreePathInner<'b, B>, } -impl<'b, B: AsRef<[u8]>> Display for SubtreePath<'b, B> { +impl> Display for SubtreePath<'_, B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let path = self.to_vec(); @@ -98,7 +98,7 @@ pub(crate) enum SubtreePathInner<'b, B> { SubtreePathIter(SubtreePathIter<'b, B>), } -impl<'bl, 'br, BL, BR> PartialEq> for SubtreePath<'bl, BL> +impl<'br, BL, BR> PartialEq> for SubtreePath<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -115,7 +115,7 @@ where /// can guarantee is to be free of false equality; however, seemingly unrelated /// subtrees can come one after another if they share the same length, which was /// (not) done for performance reasons. -impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePath<'bl, BL> +impl<'br, BL, BR> PartialOrd> for SubtreePath<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -134,7 +134,7 @@ where } } -impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePathBuilder<'bl, BL> +impl<'br, BL, BR> PartialOrd> for SubtreePathBuilder<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -153,7 +153,7 @@ where } } -impl<'bl, 'br, BL, BR> PartialOrd> for SubtreePath<'bl, BL> +impl<'br, BL, BR> PartialOrd> for SubtreePath<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -163,7 +163,7 @@ where } } -impl<'bl, BL> Ord for SubtreePath<'bl, BL> +impl Ord for SubtreePath<'_, BL> where BL: AsRef<[u8]>, { @@ -172,7 +172,7 @@ where } } -impl<'bl, BL> Ord for SubtreePathBuilder<'bl, BL> +impl Ord for SubtreePathBuilder<'_, BL> where BL: AsRef<[u8]>, { @@ -181,7 +181,7 @@ where } } -impl<'b, B: AsRef<[u8]>> Eq for SubtreePath<'b, B> {} +impl> Eq for SubtreePath<'_, B> {} impl<'b, B> From> for SubtreePath<'b, B> { fn from(ref_variant: SubtreePathInner<'b, B>) -> Self { @@ -211,7 +211,7 @@ impl<'s, 'b, B> From<&'s SubtreePathBuilder<'b, B>> for SubtreePath<'s, B> { /// Hash order is the same as iteration order: from most deep path segment up to /// root. -impl<'b, B: AsRef<[u8]>> Hash for SubtreePath<'b, B> { +impl> Hash for SubtreePath<'_, B> { fn hash(&self, state: &mut H) { match &self.ref_variant { SubtreePathInner::Slice(slice) => slice diff --git a/path/src/subtree_path_builder.rs b/path/src/subtree_path_builder.rs index f3a7d5538..d834a5f32 100644 --- a/path/src/subtree_path_builder.rs +++ b/path/src/subtree_path_builder.rs @@ -46,7 +46,7 @@ pub struct SubtreePathBuilder<'b, B> { pub(crate) relative: SubtreePathRelative<'b>, } -impl<'b, B> Clone for SubtreePathBuilder<'b, B> { +impl Clone for SubtreePathBuilder<'_, B> { fn clone(&self) -> Self { SubtreePathBuilder { base: self.base.clone(), @@ -57,14 +57,14 @@ impl<'b, B> Clone for SubtreePathBuilder<'b, B> { /// Hash order is the same as iteration order: from most deep path segment up to /// root. -impl<'b, B: AsRef<[u8]>> Hash for SubtreePathBuilder<'b, B> { +impl> Hash for SubtreePathBuilder<'_, B> { fn hash(&self, state: &mut H) { self.relative.hash(state); self.base.hash(state); } } -impl<'bl, 'br, BL, BR> PartialEq> for SubtreePathBuilder<'bl, BL> +impl<'br, BL, BR> PartialEq> for SubtreePathBuilder<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -74,7 +74,7 @@ where } } -impl<'bl, 'br, BL, BR> PartialEq> for SubtreePath<'bl, BL> +impl<'br, BL, BR> PartialEq> for SubtreePath<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -84,7 +84,7 @@ where } } -impl<'bl, 'br, BL, BR> PartialEq> for SubtreePathBuilder<'bl, BL> +impl<'br, BL, BR> PartialEq> for SubtreePathBuilder<'_, BL> where BL: AsRef<[u8]>, BR: AsRef<[u8]>, @@ -94,7 +94,7 @@ where } } -impl<'b, B: AsRef<[u8]>> Eq for SubtreePathBuilder<'b, B> {} +impl> Eq for SubtreePathBuilder<'_, B> {} impl<'s, 'b, B> From<&'s SubtreePath<'b, B>> for SubtreePathBuilder<'b, B> { fn from(value: &'s SubtreePath<'b, B>) -> Self { @@ -158,7 +158,7 @@ impl Default for SubtreePathBuilder<'static, [u8; 0]> { } } -impl<'b, B> SubtreePathBuilder<'b, B> { +impl SubtreePathBuilder<'_, B> { /// Makes an owned `SubtreePathBuilder` out of iterator. pub fn owned_from_iter>(iter: impl IntoIterator) -> Self { let bytes = iter.into_iter().fold(CompactBytes::new(), |mut bytes, s| { @@ -175,7 +175,7 @@ impl<'b, B> SubtreePathBuilder<'b, B> { } /// Create an owned version of `SubtreePathBuilder` from `SubtreePath`. - pub fn owned_from_path<'a, S: AsRef<[u8]>>(path: SubtreePath<'a, S>) -> Self { + pub fn owned_from_path>(path: SubtreePath) -> Self { Self::owned_from_iter(path.to_vec()) } } @@ -240,9 +240,10 @@ impl<'b, B: AsRef<[u8]>> SubtreePathBuilder<'b, B> { } } - /// Get a derived path for a parent and a chopped segment. The lifetime of returned path is - /// constrained solely by the original slice that this whole path hierarchy is based upon, and the point - /// of derivation has no effect on it. + /// Get a derived path for a parent and a chopped segment. The lifetime of + /// returned path is constrained solely by the original slice that this + /// whole path hierarchy is based upon, and the point of derivation has + /// no effect on it. pub fn derive_parent_owned(&self) -> Option<(SubtreePathBuilder<'b, B>, Vec)> { match &self.relative { SubtreePathRelative::Empty => self diff --git a/storage/src/storage.rs b/storage/src/storage.rs index 3a0b54852..ede8f0c69 100644 --- a/storage/src/storage.rs +++ b/storage/src/storage.rs @@ -314,6 +314,11 @@ impl StorageBatch { + operations.meta.len() } + /// Returns true if the batch is empty + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Add deferred `put` operation pub(crate) fn put( &self, From 2749b442daa7d96f879c98df55b64089956e6fce Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Fri, 27 Dec 2024 18:48:51 +0100 Subject: [PATCH 8/9] address complex type clippy warning in merk cache --- grovedb/src/merk_cache.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/grovedb/src/merk_cache.rs b/grovedb/src/merk_cache.rs index 993a95912..c6a41e640 100644 --- a/grovedb/src/merk_cache.rs +++ b/grovedb/src/merk_cache.rs @@ -15,13 +15,17 @@ use crate::{Error, GroveDb, Transaction}; type TxMerk<'db> = Merk>; +/// We store Merk on heap to preserve its location as well as borrow flag +/// alongside. +type CachedMerkEntry<'db> = Box<(Cell, TxMerk<'db>)>; + /// Structure to keep subtrees open in memory for repeated access. pub(crate) struct MerkCache<'db, 'b, B: AsRef<[u8]>> { db: &'db GroveDb, pub(crate) version: &'db GroveVersion, batch: Box, tx: &'db Transaction<'db>, - merks: UnsafeCell, Box<(Cell, TxMerk<'db>)>>>, + merks: UnsafeCell, CachedMerkEntry<'db>>>, } impl<'db, 'b, B: AsRef<[u8]>> MerkCache<'db, 'b, B> { @@ -171,7 +175,7 @@ pub(crate) struct MerkHandle<'db, 'c> { taken_handle: &'c Cell, } -impl<'db, 'c> MerkHandle<'db, 'c> { +impl<'db> MerkHandle<'db, '_> { pub(crate) fn for_merk(&mut self, f: impl FnOnce(&mut TxMerk<'db>) -> T) -> T { if self.taken_handle.get() { panic!("Attempt to have double &mut borrow on Merk"); From 55acd042a0ba4b850a343318d4397ee2289ab746 Mon Sep 17 00:00:00 2001 From: Evgeny Fomin Date: Sat, 28 Dec 2024 09:12:24 +0100 Subject: [PATCH 9/9] fix doc warning --- costs/src/context.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/costs/src/context.rs b/costs/src/context.rs index 8224cb888..d661e3a1d 100644 --- a/costs/src/context.rs +++ b/costs/src/context.rs @@ -179,7 +179,7 @@ impl CostsExt for T {} /// 1. Early termination on error; /// 2. Because of 1, `Result` is removed from the equation; /// 3. `CostContext` is removed too because it is added to external cost -/// accumulator; +/// accumulator; /// 4. Early termination uses external cost accumulator so previous costs won't /// be lost. #[macro_export]