{"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\n", "middle": "mod builder;\n", "suffix": "mod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.tran", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\n", "middle": "mod consensus;\n", "suffix": "mod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\n", "middle": "mod execute;\n", "suffix": "mod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\n", "middle": "mod network;\n", "suffix": "mod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\n", "middle": "mod payload;\n", "suffix": "mod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\n", "middle": "mod pool;\n", "suffix": "\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Mod"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\n", "middle": "pub use builder::*;\n", "suffix": "pub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\n", "middle": "pub use consensus::*;\n", "suffix": "pub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.con", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\n", "middle": "pub use execute::*;\n", "suffix": "pub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n ", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\n", "middle": "pub use network::*;\n", "suffix": "pub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\n", "middle": "pub use payload::*;\n", "suffix": "pub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\n", "middle": "pub use pool::*;\n", "suffix": "\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_b", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\n", "middle": "use crate::{ConfigureEvm, FullNodeTypes};\n", "suffix": "use reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\n", "middle": "use reth_consensus::FullConsensus;\n", "suffix": "use reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\n", "middle": "use reth_network::types::NetPrimitivesFor;\n", "suffix": "use reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\n", "middle": "use reth_network_api::FullNetwork;\n", "suffix": "use reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\n", "middle": "use reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\n", "suffix": "use reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\n", "middle": "use reth_payload_builder::PayloadBuilderHandle;\n", "suffix": "use reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\n", "middle": "use reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\n", "suffix": "use std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\n", "middle": "use std::fmt::Debug;\n", "suffix": "\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n", "middle": " fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n", "suffix": "\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool ", "middle": "{\n &self.transaction_pool\n }", "suffix": "\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n", "middle": " fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n", "suffix": "\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm ", "middle": "{\n &self.evm_config\n }", "suffix": "\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n", "middle": " fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n", "suffix": "\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus ", "middle": "{\n &self.consensus\n }", "suffix": "\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n", "middle": " fn network(&self) -> &Self::Network {\n &self.network\n }\n", "suffix": "\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network ", "middle": "{\n &self.network\n }", "suffix": "\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n", "middle": " fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n", "suffix": "}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "onfiguring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> ", "middle": "{\n &self.payload_builder_handle\n }", "suffix": "\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n", "middle": " fn clone(&self) -> Self {\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/components/mod.rs", "prefix": "//! Support for configuring the components of a node.\n//!\n//! Customizable components of the node include:\n//! - The transaction pool.\n//! - The network implementation.\n//! - The payload builder service.\n//!\n//! Components depend on a fully type configured node: [FullNodeTypes](crate::node::FullNodeTypes).\n\nmod builder;\nmod consensus;\nmod execute;\nmod network;\nmod payload;\nmod pool;\n\npub use builder::*;\npub use consensus::*;\npub use execute::*;\npub use network::*;\npub use payload::*;\npub use pool::*;\n\nuse crate::{ConfigureEvm, FullNodeTypes};\nuse reth_consensus::FullConsensus;\nuse reth_network::types::NetPrimitivesFor;\nuse reth_network_api::FullNetwork;\nuse reth_node_api::{NodeTypes, PrimitivesTy, TxTy};\nuse reth_payload_builder::PayloadBuilderHandle;\nuse reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};\nuse std::fmt::Debug;\n\n/// An abstraction over the components of a node, consisting of:\n/// - evm and executor\n/// - transaction pool\n/// - network\n/// - payload builder.\npub trait NodeComponents: Clone + Debug + Unpin + Send + Sync + 'static {\n /// The transaction pool of the node.\n type Pool: TransactionPool>> + Unpin;\n\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n type Evm: ConfigureEvm::Primitives>;\n\n /// The consensus type of the node.\n type Consensus: FullConsensus<::Primitives> + Clone + Unpin + 'static;\n\n /// Network API.\n type Network: FullNetwork::Primitives>>;\n\n /// Returns the transaction pool of the node.\n fn pool(&self) -> &Self::Pool;\n\n /// Returns the node's evm config.\n fn evm_config(&self) -> &Self::Evm;\n\n /// Returns the node's consensus type.\n fn consensus(&self) -> &Self::Consensus;\n\n /// Returns the handle to the network\n fn network(&self) -> &Self::Network;\n\n /// Returns the handle to the payload builder service handling payload building requests from\n /// the engine.\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload>;\n}\n\n/// All the components of the node.\n///\n/// This provides access to all the components of the node.\n#[derive(Debug)]\npub struct Components {\n /// The transaction pool of the node.\n pub transaction_pool: Pool,\n /// The node's EVM configuration, defining settings for the Ethereum Virtual Machine.\n pub evm_config: EVM,\n /// The consensus implementation of the node.\n pub consensus: Consensus,\n /// The network implementation of the node.\n pub network: Network,\n /// The handle to the payload builder service.\n pub payload_builder_handle: PayloadBuilderHandle<::Payload>,\n}\n\nimpl NodeComponents\n for Components\nwhere\n Node: FullNodeTypes,\n Network: FullNetwork<\n Primitives: NetPrimitivesFor<\n PrimitivesTy,\n PooledTransaction = PoolPooledTx,\n >,\n >,\n Pool: TransactionPool>>\n + Unpin\n + 'static,\n EVM: ConfigureEvm> + 'static,\n Cons: FullConsensus> + Clone + Unpin + 'static,\n{\n type Pool = Pool;\n type Evm = EVM;\n type Consensus = Cons;\n type Network = Network;\n\n fn pool(&self) -> &Self::Pool {\n &self.transaction_pool\n }\n\n fn evm_config(&self) -> &Self::Evm {\n &self.evm_config\n }\n\n fn consensus(&self) -> &Self::Consensus {\n &self.consensus\n }\n\n fn network(&self) -> &Self::Network {\n &self.network\n }\n\n fn payload_builder_handle(&self) -> &PayloadBuilderHandle<::Payload> {\n &self.payload_builder_handle\n }\n}\n\nimpl Clone for Components\nwhere\n N: Clone,\n Node: FullNodeTypes,\n Pool: TransactionPool,\n EVM: ConfigureEvm,\n Cons: Clone,\n{\n fn clone(&self) -> Self ", "middle": "{\n Self {\n transaction_pool: self.transaction_pool.clone(),\n evm_config: self.evm_config.clone(),\n consensus: self.consensus.clone(),\n network: self.network.clone(),\n payload_builder_handle: self.payload_builder_handle.clone(),\n }\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "", "middle": "use super::error::HeadersDownloaderResult;\n", "suffix": "use crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\n", "middle": "use crate::error::{DownloadError, DownloadResult};\n", "suffix": "use alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\n", "middle": "use alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\n", "suffix": "use alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n ", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\n", "middle": "use alloy_primitives::{Sealable, B256};\n", "suffix": "use futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: heade", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\n", "middle": "use futures::Stream;\n", "suffix": "use reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\n", "middle": "use reth_consensus::HeaderValidator;\n", "suffix": "use reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\n", "middle": "use reth_primitives_traits::{BlockHeader, Header, SealedHeader};\n", "suffix": "use std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\n", "middle": "use std::fmt::Debug;\n", "suffix": "\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error|", "nodeType": "Use"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\n", "middle": "impl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n", "suffix": "\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n", "middle": " pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n", "suffix": "}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Function"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber ", "middle": "{\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }", "suffix": "\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n", "middle": "/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n", "suffix": "\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Struct"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\n", "middle": "impl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n}\n", "suffix": "\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n", "middle": " pub fn is_closed(&self) -> bool {\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }\n", "suffix": "}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "Function"} {"filePath": "crates/net/p2p/src/headers/downloader.rs", "prefix": "use super::error::HeadersDownloaderResult;\nuse crate::error::{DownloadError, DownloadResult};\nuse alloy_eips::{eip1898::BlockWithParent, BlockHashOrNumber};\nuse alloy_primitives::{Sealable, B256};\nuse futures::Stream;\nuse reth_consensus::HeaderValidator;\nuse reth_primitives_traits::{BlockHeader, Header, SealedHeader};\nuse std::fmt::Debug;\n\n/// A downloader capable of fetching and yielding block headers.\n///\n/// A downloader represents a distinct strategy for submitting requests to download block headers,\n/// while a [`HeadersClient`][crate::headers::client::HeadersClient] represents a client capable\n/// of fulfilling these requests.\n///\n/// A [`HeaderDownloader`] is a [Stream] that returns batches of headers.\npub trait HeaderDownloader:\n Send\n + Sync\n + Stream>, Self::Header>>\n + Unpin\n{\n /// The header type being downloaded.\n type Header: Sealable + Debug + Send + Sync + Unpin + 'static;\n\n /// Updates the gap to sync which ranges from local head to the sync target.\n ///\n /// See also [`HeaderDownloader::update_sync_target`] and\n /// [`HeaderDownloader::update_local_head`]\n fn update_sync_gap(&mut self, head: SealedHeader, target: SyncTarget) {\n self.update_local_head(head);\n self.update_sync_target(target);\n }\n\n /// Updates the block number of the local database\n fn update_local_head(&mut self, head: SealedHeader);\n\n /// Updates the target we want to sync to.\n fn update_sync_target(&mut self, target: SyncTarget);\n\n /// Sets the headers batch size that the Stream should return.\n fn set_batch_size(&mut self, limit: usize);\n}\n\n/// Specifies the target to sync for [`HeaderDownloader::update_sync_target`]\n#[derive(Debug, Clone, Eq, PartialEq)]\npub enum SyncTarget {\n /// This represents a range missing headers in the form of `(head,..`\n ///\n /// Sync _inclusively_ to the given block hash.\n ///\n /// This target specifies the upper end of the sync gap `(head...tip]`\n Tip(B256),\n /// This represents a gap missing headers bounded by the given header `h` in the form of\n /// `(head,..h),h+1,h+2...`\n ///\n /// Sync _exclusively_ to the given header's parent which is: `(head..h-1]`\n ///\n /// The benefit of this variant is, that this already provides the block number of the highest\n /// missing block.\n Gap(BlockWithParent),\n /// This represents a tip by block number\n TipNum(u64),\n}\n\n// === impl SyncTarget ===\n\nimpl SyncTarget {\n /// Returns the tip to sync to _inclusively_\n ///\n /// This returns the hash if the target is [`SyncTarget::Tip`] or the `parent_hash` of the given\n /// header in [`SyncTarget::Gap`]\n pub fn tip(&self) -> BlockHashOrNumber {\n match self {\n Self::Tip(tip) => (*tip).into(),\n Self::Gap(gap) => gap.parent.into(),\n Self::TipNum(num) => (*num).into(),\n }\n }\n}\n\n/// Represents a gap to sync: from `local_head` to `target`\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct HeaderSyncGap {\n /// The local head block. Represents lower bound of sync range.\n pub local_head: SealedHeader,\n\n /// The sync target. Represents upper bound of sync range.\n pub target: SyncTarget,\n}\n\nimpl HeaderSyncGap {\n /// Returns `true` if the gap from the head to the target was closed\n #[inline]\n pub fn is_closed(&self) -> bool ", "middle": "{\n match self.target.tip() {\n BlockHashOrNumber::Hash(hash) => self.local_head.hash() == hash,\n BlockHashOrNumber::Number(num) => self.local_head.number() == num,\n }\n }", "suffix": "\n}\n\n/// Validate whether the header is valid in relation to its parent.\npub fn validate_header_download(\n consensus: &dyn HeaderValidator,\n header: &SealedHeader,\n parent: &SealedHeader,\n) -> DownloadResult<()> {\n // validate header against parent\n consensus.validate_header_against_parent(header, parent).map_err(|error| {\n DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n }\n })?;\n // validate header standalone\n consensus.validate_header(header).map_err(|error| DownloadError::HeaderValidation {\n hash: header.hash(),\n number: header.number(),\n error: Box::new(error),\n })?;\n Ok(())\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "", "middle": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\n", "suffix": "use reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\n", "middle": "use reth_cli::chainspec::{parse_genesis, ChainSpecParser};\n", "suffix": "use std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\n", "middle": "use std::sync::Arc;\n", "suffix": "\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n", "middle": "/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n", "suffix": "\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Const"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\n", "middle": "pub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n", "suffix": "\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> ", "middle": "{\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}", "suffix": "\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n", "middle": "/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n", "suffix": "\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\n", "middle": "impl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n", "suffix": "\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n", "middle": " fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n", "suffix": "}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> ", "middle": "{\n chain_value_parser(s)\n }", "suffix": "\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::*;\n", "suffix": " use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n", "middle": " use reth_chainspec::EthereumHardforks;\n", "suffix": "\n #[test]\n fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n", "middle": " fn parse_known_chain_spec() {\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }\n", "suffix": "\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/ethereum/cli/src/chainspec.rs", "prefix": "use reth_chainspec::{ChainSpec, DEV, HOLESKY, HOODI, MAINNET, SEPOLIA};\nuse reth_cli::chainspec::{parse_genesis, ChainSpecParser};\nuse std::sync::Arc;\n\n/// Chains supported by reth. First value should be used as the default.\npub const SUPPORTED_CHAINS: &[&str] = &[\"mainnet\", \"sepolia\", \"holesky\", \"hoodi\", \"dev\"];\n\n/// Clap value parser for [`ChainSpec`]s.\n///\n/// The value parser matches either a known chain, the path\n/// to a json file, or a json formatted string in-memory. The json needs to be a Genesis struct.\npub fn chain_value_parser(s: &str) -> eyre::Result, eyre::Error> {\n Ok(match s {\n \"mainnet\" => MAINNET.clone(),\n \"sepolia\" => SEPOLIA.clone(),\n \"holesky\" => HOLESKY.clone(),\n \"hoodi\" => HOODI.clone(),\n \"dev\" => DEV.clone(),\n _ => Arc::new(parse_genesis(s)?.into()),\n })\n}\n\n/// Ethereum chain specification parser.\n#[derive(Debug, Clone, Default)]\n#[non_exhaustive]\npub struct EthereumChainSpecParser;\n\nimpl ChainSpecParser for EthereumChainSpecParser {\n type ChainSpec = ChainSpec;\n\n const SUPPORTED_CHAINS: &'static [&'static str] = SUPPORTED_CHAINS;\n\n fn parse(s: &str) -> eyre::Result> {\n chain_value_parser(s)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use reth_chainspec::EthereumHardforks;\n\n #[test]\n fn parse_known_chain_spec() ", "middle": "{\n for &chain in EthereumChainSpecParser::SUPPORTED_CHAINS {\n assert!(::parse(chain).is_ok());\n }\n }", "suffix": "\n\n #[test]\n fn parse_raw_chainspec_hardforks() {\n let s = r#\"{\n \"parentHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"uncleHash\": \"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\n \"coinbase\": \"0x0000000000000000000000000000000000000000\",\n \"stateRoot\": \"0x76f118cb05a8bc558388df9e3b4ad66ae1f17ef656e5308cb8f600717251b509\",\n \"transactionsTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"receiptTrie\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"bloom\": \"0x000...000\",\n \"difficulty\": \"0x00\",\n \"number\": \"0x00\",\n \"gasLimit\": \"0x016345785d8a0000\",\n \"gasUsed\": \"0x00\",\n \"timestamp\": \"0x01\",\n \"extraData\": \"0x00\",\n \"mixHash\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"nonce\": \"0x0000000000000000\",\n \"baseFeePerGas\": \"0x07\",\n \"withdrawalsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"blobGasUsed\": \"0x00\",\n \"excessBlobGas\": \"0x00\",\n \"parentBeaconBlockRoot\": \"0x0000000000000000000000000000000000000000000000000000000000000000\",\n \"requestsRoot\": \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\",\n \"hash\": \"0xc20e1a771553139cdc77e6c3d5f64a7165d972d327eee9632c9c7d0fe839ded4\",\n \"alloc\": {},\n \"config\": {\n \"ethash\": {},\n \"chainId\": 1,\n \"homesteadBlock\": 0,\n \"daoForkSupport\": true,\n \"eip150Block\": 0,\n \"eip155Block\": 0,\n \"eip158Block\": 0,\n \"byzantiumBlock\": 0,\n \"constantinopleBlock\": 0,\n \"petersburgBlock\": 0,\n \"istanbulBlock\": 0,\n \"berlinBlock\": 0,\n \"londonBlock\": 0,\n \"terminalTotalDifficulty\": 0,\n \"shanghaiTime\": 0,\n \"cancunTime\": 0,\n \"pragueTime\": 0,\n \"osakaTime\": 0\n }\n}\"#;\n\n let spec = ::parse(s).unwrap();\n assert!(spec.is_shanghai_active_at_timestamp(0));\n assert!(spec.is_cancun_active_at_timestamp(0));\n assert!(spec.is_prague_active_at_timestamp(0));\n assert!(spec.is_osaka_active_at_timestamp(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\n", "middle": "use crate::Metrics;\n", "suffix": "use futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedP", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\n", "middle": "use futures::Stream;\n", "suffix": "use metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Cr", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\n", "middle": "use metrics::Counter;\n", "suffix": "use reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPe", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\n", "middle": "use reth_primitives_traits::InMemorySize;\n", "suffix": "use std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`m", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\n", "middle": "use std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\n", "suffix": "use tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\n", "middle": "use tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\n", "suffix": "use tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\n", "middle": "use tokio_util::sync::{PollSendError, PollSender};\n", "suffix": "\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n ", "nodeType": "Use"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\n", "middle": "pub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n", "suffix": "\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetr", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) ", "middle": "{\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}", "suffix": "\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sendi", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\n", "middle": "pub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n", "suffix": "\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// S", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) ", "middle": "{\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}", "suffix": "\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n", "middle": "/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n", "suffix": "\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n ", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\n", "middle": "impl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n", "suffix": "\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n", "middle": " pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n", "suffix": "\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self ", "middle": "{\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }", "suffix": "\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n", "middle": " pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n", "suffix": "}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &s", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> ", "middle": "{\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }", "suffix": "\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\n", "middle": "impl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n", "suffix": "\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messag", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n", "middle": " fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n", "suffix": "}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(perm", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self ", "middle": "{\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }", "suffix": "\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n", "middle": "/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n", "suffix": "\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\n", "middle": "impl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n", "suffix": "\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n", "middle": " pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n", "suffix": "\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metri", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self ", "middle": "{\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }", "suffix": "\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `s", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n", "middle": " pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n", "suffix": "\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option ", "middle": "{\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }", "suffix": "\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n", "middle": " pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n", "suffix": "\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result ", "middle": "{\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }", "suffix": "\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for Mete", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n", "middle": " pub fn close(&mut self) {\n self.receiver.close();\n }\n", "suffix": "\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for t", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) ", "middle": "{\n self.receiver.close();\n }", "suffix": "\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n", "middle": " pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n", "suffix": "}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }", "suffix": "\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\n", "middle": "impl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n", "suffix": "\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n ", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "c::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n", "middle": " fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n", "suffix": "}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "rror, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n self.poll_recv(cx)\n }", "suffix": "\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the rese", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "nel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n", "middle": "/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n", "suffix": "\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.mes", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "red channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n", "middle": " pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n", "suffix": "\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "fer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self ", "middle": "{\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }", "suffix": "\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n", "middle": " pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n", "suffix": "\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "is wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> ", "middle": "{\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }", "suffix": "\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n", "middle": " pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n", "suffix": "\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "s the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> ", "middle": "{\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }", "suffix": "\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n", "middle": " pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n", "suffix": "\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstru", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ssages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> ", "middle": "{\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }", "suffix": "\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if m", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n", "middle": " pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n", "suffix": "\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// Whe", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> ", "middle": "{\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }", "suffix": "\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "Receiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n", "middle": " pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n", "suffix": "\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "etrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender ", "middle": "{\n &self.sender\n }", "suffix": "\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.re", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n", "middle": " pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n", "suffix": "\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> ", "middle": "{\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }", "suffix": "\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in th", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "nt(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n", "middle": " pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n", "suffix": "}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[der", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "}\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> ", "middle": "{\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }", "suffix": "\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dy", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "sg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\n", "middle": "impl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n", "suffix": "\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSend", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "/ Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n", "middle": " fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n", "suffix": "}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// T", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "//! Support for metering senders. Facilitates debugging by exposing metrics for number of messages\n//! sent, number of errors, etc.\n\nuse crate::Metrics;\nuse futures::Stream;\nuse metrics::Counter;\nuse reth_primitives_traits::InMemorySize;\nuse std::{\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc,\n },\n task::{ready, Context, Poll},\n};\nuse tokio::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self ", "middle": "{\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }", "suffix": "\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a differen", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n", "middle": "/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n", "suffix": "\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender<", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\n", "middle": "impl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n", "suffix": "\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n ", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "oll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n", "middle": " pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n", "suffix": "\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "o::sync::mpsc::{\n self,\n error::{SendError, TryRecvError, TrySendError},\n};\nuse tokio_util::sync::{PollSendError, PollSender};\n\n/// Wrapper around [`mpsc::unbounded_channel`] that returns a new unbounded metered channel.\npub fn metered_unbounded_channel(\n scope: &'static str,\n) -> (UnboundedMeteredSender, UnboundedMeteredReceiver) {\n let (tx, rx) = mpsc::unbounded_channel();\n (UnboundedMeteredSender::new(tx, scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self ", "middle": "{\n Self { permit, metrics }\n }", "suffix": "\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n", "middle": " pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n", "suffix": "}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": ") that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender ", "middle": "{\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }", "suffix": "\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.p", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": ", scope), UnboundedMeteredReceiver::new(rx, scope))\n}\n\n/// Wrapper around [`mpsc::channel`] that returns a new bounded metered channel with the given\n/// buffer size.\npub fn metered_channel(\n buffer: usize,\n scope: &'static str,\n) -> (MeteredSender, MeteredReceiver) {\n let (tx, rx) = mpsc::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n", "middle": "/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n", "suffix": "\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { ", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\n", "middle": "impl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n", "suffix": "\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "c::channel(buffer);\n (MeteredSender::new(tx, scope), MeteredReceiver::new(rx, scope))\n}\n\n/// A wrapper type around [`UnboundedSender`](mpsc::UnboundedSender) that updates metrics on send.\n#[derive(Debug)]\npub struct UnboundedMeteredSender {\n /// The [`UnboundedSender`](mpsc::UnboundedSender) that this wraps around\n sender: mpsc::UnboundedSender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n", "middle": " pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n", "suffix": "\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is releas", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "erve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self ", "middle": "{\n Self { permit, metrics_ref }\n }", "suffix": "\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "w(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n", "middle": " pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n", "suffix": "}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "s.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) ", "middle": "{\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }", "suffix": "\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl C", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "> UnboundedMeteredSender {\n /// Creates a new [`UnboundedMeteredSender`] wrapping around the provided\n /// [`mpsc::UnboundedSender`] that updates metrics on send.\n pub fn new(sender: mpsc::UnboundedSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Calls the underlying [`mpsc::UnboundedSender`]'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n", "middle": "/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n", "suffix": "\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\n", "middle": "impl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n", "suffix": "\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds ", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n", "middle": " pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n", "suffix": "\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate acce", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "// metrics depending on the result.\n pub fn send(&self, message: T) -> Result<(), SendError> {\n match self.sender.send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self ", "middle": "{\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }", "suffix": "\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard a", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ssages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n", "middle": " pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n", "suffix": "\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and ", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for UnboundedMeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option ", "middle": "{\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }", "suffix": "\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved b", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "T> {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n", "middle": " pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n", "suffix": "\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_re", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "elf {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`UnboundedReceiver`](mpsc::UnboundedReceiver) that updates metrics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result ", "middle": "{\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }", "suffix": "\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n", "middle": " pub fn close(&mut self) {\n self.receiver.close();\n }\n", "suffix": "\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "rics on\n/// receive.\n#[derive(Debug)]\npub struct UnboundedMeteredReceiver {\n /// The [`UnboundedReceiver`](mpsc::UnboundedReceiver) that this wraps around\n receiver: mpsc::UnboundedReceiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) ", "middle": "{\n self.receiver.close();\n }", "suffix": "\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] a", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n", "middle": " pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n", "suffix": "}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl UnboundedMeteredReceiver {\n /// Creates a new [`UnboundedMeteredReceiver`] wrapping around the provided\n /// [Receiver](mpsc::UnboundedReceiver)\n pub fn new(receiver: mpsc::UnboundedReceiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }", "suffix": "\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbou", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "f.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\n", "middle": "impl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n", "suffix": "\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the ", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ncrement(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n", "middle": " fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n", "suffix": "}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nst", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n self.poll_recv(cx)\n }", "suffix": "\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n", "middle": "/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n", "suffix": "\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's si", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n", "middle": "/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n", "suffix": "\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManage", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n", "middle": "/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n", "suffix": "\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "er: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\n", "middle": "impl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n", "suffix": "\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for UnboundedMeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n", "middle": " pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n", "suffix": "\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ing the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self ", "middle": "{\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }", "suffix": "\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// R", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n", "middle": " pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n", "suffix": "\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// A wrapper type around [Sender](mpsc::Sender) that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredSender {\n /// The [Sender](mpsc::Sender) that this wraps around\n sender: mpsc::Sender,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender ", "middle": "{\n &self.sender\n }", "suffix": "\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "e\n metrics: MeteredSenderMetrics,\n}\n\nimpl MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n", "middle": " pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n", "suffix": "\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " MeteredSender {\n /// Creates a new [`MeteredSender`] wrapping around the provided [Sender](mpsc::Sender)\n pub fn new(sender: mpsc::Sender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredSenderMetrics::new(scope) }\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve_owned`.\n pub fn try_reserve_owned(self) -> Result, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> ", "middle": "{\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }", "suffix": "\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "nedPermit, TrySendError> {\n let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n", "middle": " pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n", "suffix": "}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " let Self { sender, metrics } = self;\n sender.try_reserve_owned().map(|permit| OwnedPermit::new(permit, metrics.clone())).map_err(\n |err| match err {\n TrySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> ", "middle": "{\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }", "suffix": "\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ySendError::Full(sender) => TrySendError::Full(Self { sender, metrics }),\n TrySendError::Closed(sender) => TrySendError::Closed(Self { sender, metrics }),\n },\n )\n }\n\n /// Waits to acquire a permit to send a message and return owned permit.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve_owned`.\n pub async fn reserve_owned(self) -> Result, SendError<()>> {\n self.sender.reserve_owned().await.map(|permit| OwnedPermit::new(permit, self.metrics))\n }\n\n /// Waits to acquire a permit to send a message.\n ///\n /// See also [Sender](mpsc::Sender)'s `reserve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\n", "middle": "impl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n", "suffix": "\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n", "middle": " fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n", "suffix": "}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next messag", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "er) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self ", "middle": "{\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }", "suffix": "\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n", "middle": "/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n", "suffix": "\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_bud", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "serve`.\n pub async fn reserve(&self) -> Result, SendError<()>> {\n self.sender.reserve().await.map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Tries to acquire a permit to send a message without waiting.\n ///\n /// See also [Sender](mpsc::Sender)'s `try_reserve`.\n pub fn try_reserve(&self) -> Result, TrySendError<()>> {\n self.sender.try_reserve().map(|permit| Permit::new(permit, &self.metrics))\n }\n\n /// Returns the underlying [Sender](mpsc::Sender).\n pub const fn inner(&self) -> &mpsc::Sender {\n &self.sender\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n", "middle": "/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n", "suffix": "\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ecv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n", "middle": "/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n", "suffix": "\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(c", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "er.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\n", "middle": "impl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n", "suffix": "\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " /// Calls the underlying [Sender](mpsc::Sender)'s `try_send`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn try_send(&self, message: T) -> Result<(), TrySendError> {\n match self.sender.try_send(message) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n\n /// Calls the underlying [Sender](mpsc::Sender)'s `send`, incrementing the appropriate\n /// metrics depending on the result.\n pub async fn send(&self, value: T) -> Result<(), SendError> {\n match self.sender.send(value).await {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => {\n self.metrics.send_errors_total.increment(1);\n Err(error)\n }\n }\n }\n}\n\nimpl Clone for MeteredSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// A wrapper type around [`OwnedPermit`](mpsc::OwnedPermit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct OwnedPermit {\n permit: mpsc::OwnedPermit,\n /// Holds metrics for this type\n metrics: MeteredSenderMetrics,\n}\n\nimpl OwnedPermit {\n /// Creates a new [`OwnedPermit`] wrapping the provided [`mpsc::OwnedPermit`] with given metrics\n /// handle.\n pub const fn new(permit: mpsc::OwnedPermit, metrics: MeteredSenderMetrics) -> Self {\n Self { permit, metrics }\n }\n\n /// Sends a value using the reserved capacity and update metrics accordingly.\n pub fn send(self, value: T) -> MeteredSender {\n let Self { permit, metrics } = self;\n metrics.messages_sent_total.increment(1);\n MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n", "middle": " fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n", "suffix": "}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) ", "middle": "{\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }", "suffix": "\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n", "middle": "/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n", "suffix": "\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(Me", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n", "middle": "/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n", "suffix": "\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "ntext<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\n", "middle": "impl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n", "suffix": "\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " MeteredSender { sender: permit.send(value), metrics }\n }\n}\n\n/// A wrapper type around [Permit](mpsc::Permit) that updates metrics accounting\n/// when sending\n#[derive(Debug)]\npub struct Permit<'a, T> {\n permit: mpsc::Permit<'a, T>,\n metrics_ref: &'a MeteredSenderMetrics,\n}\n\nimpl<'a, T> Permit<'a, T> {\n /// Creates a new [`Permit`] wrapping the provided [`mpsc::Permit`] with given metrics ref.\n pub const fn new(permit: mpsc::Permit<'a, T>, metrics_ref: &'a MeteredSenderMetrics) -> Self {\n Self { permit, metrics_ref }\n }\n\n /// Sends a value using the reserved capacity and updates metrics accordingly.\n pub fn send(self, value: T) {\n self.metrics_ref.messages_sent_total.increment(1);\n self.permit.send(value);\n }\n}\n\n/// A wrapper type around [Receiver](mpsc::Receiver) that updates metrics on receive.\n#[derive(Debug)]\npub struct MeteredReceiver {\n /// The [Receiver](mpsc::Receiver) that this wraps around\n receiver: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n", "middle": " pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n", "suffix": "}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "it)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> ", "middle": "{\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }", "suffix": "\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n", "middle": "/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n", "suffix": "\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Struct"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "his type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\n", "middle": "impl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n", "suffix": "\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "r: mpsc::Receiver,\n /// Holds metrics for this type\n metrics: MeteredReceiverMetrics,\n}\n\n// === impl MeteredReceiver ===\n\nimpl MeteredReceiver {\n /// Creates a new [`MeteredReceiver`] wrapping around the provided [Receiver](mpsc::Receiver)\n pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n", "middle": " pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n", "suffix": "\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option ", "middle": "{\n self.inner.recv().await.map(unwrap_budgeted)\n }", "suffix": "\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": " pub fn new(receiver: mpsc::Receiver, scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n", "middle": " pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n", "suffix": "}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": ", scope: &'static str) -> Self {\n Self { receiver, metrics: MeteredReceiverMetrics::new(scope) }\n }\n\n /// Receives the next value for this receiver.\n pub async fn recv(&mut self) -> Option {\n let msg = self.receiver.recv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }", "suffix": "\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "bug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\n", "middle": "fn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n", "suffix": "\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "cv().await;\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n msg\n }\n\n /// Tries to receive the next value for this receiver.\n pub fn try_recv(&mut self) -> Result {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T ", "middle": "{\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}", "suffix": "\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\n", "middle": "impl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n", "suffix": "\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Impl"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": ", TryRecvError> {\n let msg = self.receiver.try_recv()?;\n self.metrics.messages_received_total.increment(1);\n Ok(msg)\n }\n\n /// Closes the receiving half of a channel without dropping it.\n pub fn close(&mut self) {\n self.receiver.close();\n }\n\n /// Polls to receive the next message on this channel.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n let msg = ready!(self.receiver.poll_recv(cx));\n if msg.is_some() {\n self.metrics.messages_received_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n", "middle": " fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n", "suffix": "}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "r.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n self.poll_recv(cx)\n }", "suffix": "\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "d_total.increment(1);\n }\n Poll::Ready(msg)\n }\n}\n\nimpl Stream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\n", "middle": "pub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) {\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}\n", "suffix": "", "nodeType": "Function"} {"filePath": "crates/metrics/src/common/mpsc.rs", "prefix": "tream for MeteredReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Throughput metrics for [`MeteredSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\npub struct MeteredSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of failed message deliveries\n send_errors_total: Counter,\n}\n\n/// Throughput metrics for [`MeteredReceiver`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredReceiverMetrics {\n /// Number of messages received\n messages_received_total: Counter,\n}\n\n/// A wrapper type around [`PollSender`] that updates metrics on send.\n#[derive(Debug)]\npub struct MeteredPollSender {\n /// The [`PollSender`] that this wraps around.\n sender: PollSender,\n /// Holds metrics for this type.\n metrics: MeteredPollSenderMetrics,\n}\n\nimpl MeteredPollSender {\n /// Creates a new [`MeteredPollSender`] wrapping around the provided [`PollSender`].\n pub fn new(sender: PollSender, scope: &'static str) -> Self {\n Self { sender, metrics: MeteredPollSenderMetrics::new(scope) }\n }\n\n /// Returns the underlying [`PollSender`].\n pub const fn inner(&self) -> &PollSender {\n &self.sender\n }\n\n /// Calls the underlying [`PollSender`]'s `poll_reserve`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> {\n match self.sender.poll_reserve(cx) {\n Poll::Ready(Ok(permit)) => Poll::Ready(Ok(permit)),\n Poll::Ready(Err(error)) => Poll::Ready(Err(error)),\n Poll::Pending => {\n self.metrics.back_pressure_total.increment(1);\n Poll::Pending\n }\n }\n }\n\n /// Calls the underlying [`PollSender`]'s `send_item`, incrementing the appropriate\n /// metrics depending on the result.\n pub fn send_item(&mut self, item: T) -> Result<(), PollSendError> {\n match self.sender.send_item(item) {\n Ok(()) => {\n self.metrics.messages_sent_total.increment(1);\n Ok(())\n }\n Err(error) => Err(error),\n }\n }\n}\n\nimpl Clone for MeteredPollSender {\n fn clone(&self) -> Self {\n Self { sender: self.sender.clone(), metrics: self.metrics.clone() }\n }\n}\n\n/// Throughput metrics for [`MeteredPollSender`]\n#[derive(Clone, Metrics)]\n#[metrics(dynamic = true)]\nstruct MeteredPollSenderMetrics {\n /// Number of messages sent\n messages_sent_total: Counter,\n /// Number of delayed message deliveries caused by a full channel\n back_pressure_total: Counter,\n}\n\n/// Shared state for tracking memory budget across sender and receiver.\n///\n/// `used` is a pure accounting counter \u2014 it does not gate access to any other\n/// shared memory, so all operations on it use [`Ordering::Relaxed`]. Cross-thread\n/// publication of message contents is handled by the underlying mpsc channel.\n#[derive(Debug)]\nstruct MemoryBudget {\n /// Current number of bytes used by buffered messages.\n used: AtomicUsize,\n /// Maximum allowed bytes.\n max_bytes: usize,\n}\n\n/// Guard that releases memory budget when dropped.\n///\n/// Holds the size of the message and a reference to the shared budget counter.\n/// When dropped, it atomically decreases the used counter.\n#[derive(Debug)]\nstruct BudgetGuard {\n size: usize,\n budget: Arc,\n}\n\nimpl Drop for BudgetGuard {\n fn drop(&mut self) {\n self.budget.used.fetch_sub(self.size, Ordering::Relaxed);\n }\n}\n\n/// Message envelope that holds the memory budget while the message sits in the channel.\n///\n/// The guard is dropped (releasing the budget) as soon as the receiver dequeues\n/// the message via [`MemoryBoundedReceiver::recv`] / [`MemoryBoundedReceiver::poll_recv`],\n/// so the budget tracks bytes *currently in the channel queue*, not bytes in flight\n/// downstream of the receiver.\n#[derive(Debug)]\nstruct Budgeted {\n msg: T,\n _guard: BudgetGuard,\n}\n\n/// A sender that enforces a byte budget before enqueueing messages.\n///\n/// Uses a shared atomic counter to track memory usage. Each message's size is added\n/// to the counter on send and subtracted when the message is dequeued by the receiver.\n///\n/// The current call sites (specifically [`crate::common::mpsc::MemoryBoundedSender`] used\n/// for the `NetworkManager \u2192 TransactionsManager` channel) have a single producer driven\n/// from a single `poll`, so the `fetch_add \u2192 check \u2192 fetch_sub-on-overflow` reservation\n/// pattern can never race with itself. The atomic is still used so the receiver can\n/// release budget from a different task.\n#[derive(Debug, Clone)]\npub struct MemoryBoundedSender {\n /// The underlying unbounded metered sender\n inner: UnboundedMeteredSender>,\n /// Shared memory budget tracker\n budget: Arc,\n}\n\nimpl MemoryBoundedSender {\n /// Tries to send a message if there is sufficient budget.\n ///\n /// Returns `TrySendError::Full` if insufficient budget is available.\n pub fn try_send(&self, msg: T) -> Result<(), TrySendError> {\n let size = msg.size();\n\n // Reserve budget: add first, check after\n let prev = self.budget.used.fetch_add(size, Ordering::Relaxed);\n if prev.saturating_add(size) > self.budget.max_bytes {\n // Over budget, undo\n self.budget.used.fetch_sub(size, Ordering::Relaxed);\n return Err(TrySendError::Full(msg));\n }\n\n let guard = BudgetGuard { size, budget: Arc::clone(&self.budget) };\n let budgeted = Budgeted { msg, _guard: guard };\n\n self.inner.send(budgeted).map_err(|e| {\n // Guard will be dropped here, releasing the budget\n TrySendError::Closed(e.0.msg)\n })\n }\n}\n\n/// A receiver for memory-bounded messages.\n///\n/// On receive, the budget reserved for the message is released immediately and the\n/// inner `T` is yielded \u2014 callers do not need to opt into any wrapper type.\n#[derive(Debug)]\npub struct MemoryBoundedReceiver {\n /// The underlying unbounded metered receiver\n inner: UnboundedMeteredReceiver>,\n}\n\nimpl MemoryBoundedReceiver {\n /// Receives the next message, returning `None` if the channel is closed.\n ///\n /// Releases the message's reserved budget before returning.\n pub async fn recv(&mut self) -> Option {\n self.inner.recv().await.map(unwrap_budgeted)\n }\n\n /// Polls to receive the next message on this channel.\n ///\n /// Releases the message's reserved budget before returning.\n pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll> {\n self.inner.poll_recv(cx).map(|opt| opt.map(unwrap_budgeted))\n }\n}\n\n/// Releases the budget guard and returns the inner message.\nfn unwrap_budgeted(b: Budgeted) -> T {\n // Destructuring binds `_guard` so it is dropped when this function returns,\n // which runs `BudgetGuard::drop` and releases the reserved bytes.\n let Budgeted { msg, _guard } = b;\n msg\n}\n\nimpl Stream for MemoryBoundedReceiver {\n type Item = T;\n\n fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n self.poll_recv(cx)\n }\n}\n\n/// Creates a new memory-bounded channel with the given byte budget.\n///\n/// The budget tracks bytes currently buffered in the channel; it is reserved on\n/// [`MemoryBoundedSender::try_send`] and released as soon as the receiver dequeues\n/// the message.\npub fn memory_bounded_channel(\n max_bytes: usize,\n scope: &'static str,\n) -> (MemoryBoundedSender, MemoryBoundedReceiver) ", "middle": "{\n let (tx, rx) = metered_unbounded_channel(scope);\n let budget = Arc::new(MemoryBudget { used: AtomicUsize::new(0), max_bytes });\n\n let sender = MemoryBoundedSender { inner: tx, budget };\n let receiver = MemoryBoundedReceiver { inner: rx };\n\n (sender, receiver)\n}", "suffix": "\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\n", "middle": "use std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\n", "suffix": "use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R ", "nodeType": "Use"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\n", "middle": "use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n", "suffix": "\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n }", "nodeType": "Use"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n", "middle": "/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n", "suffix": "\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\n", "middle": "impl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n", "suffix": "\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n", "middle": " pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n", "suffix": "\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) =", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self ", "middle": "{\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }", "suffix": "\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n", "middle": " pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n", "suffix": "\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n ", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result ", "middle": "{\n self.0.acquire_owned().await\n }", "suffix": "\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n", "middle": " pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n", "suffix": "}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub str", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result ", "middle": "{\n self.0.acquire_many_owned(n).await\n }", "suffix": "\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with ac", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n", "middle": "/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n", "suffix": "\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n", "middle": " pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n", "suffix": "\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self ", "middle": "{\n Self { pool: Arc::new(pool) }\n }", "suffix": "\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n", "middle": " pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n", "suffix": "\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pu", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder ", "middle": "{\n rayon::ThreadPoolBuilder::new()\n }", "suffix": "\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'sco", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n", "middle": " pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n", "suffix": "\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result ", "middle": "{\n Self::builder().build().map(Self::new)\n }", "suffix": "\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"fa", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n", "middle": " pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n", "suffix": "\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n bui", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n ", "middle": "{\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }", "suffix": "\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_t", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n", "middle": " pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n", "suffix": "}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().br", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n ", "middle": "{\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }", "suffix": "\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n", "middle": "/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n", "suffix": "\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxe", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\n", "middle": "impl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n", "suffix": "\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ", "nodeType": "Impl"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "-> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n", "middle": " fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n", "suffix": "}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => br", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "re::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll ", "middle": "{\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }", "suffix": "\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "emaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n", "middle": "/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n", "suffix": "\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n", "middle": "/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n", "suffix": "\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n ", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "art building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n", "middle": " pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n", "suffix": "\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scop", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self ", "middle": "{\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }", "suffix": "\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_pa", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "ured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n", "middle": " fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n", "suffix": "\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool ", "middle": "{\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }", "suffix": "\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n", "middle": " pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n", "suffix": "\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) ", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool ", "middle": "{\n self.pool.get().is_some()\n }", "suffix": "\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broa", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n", "middle": " pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n", "suffix": "\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Ru", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize ", "middle": "{\n self.pool().current_num_threads()\n }", "suffix": "\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n", "middle": " pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n", "suffix": "\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1,", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "//! Additional helpers for executing tracing calls\n\nuse std::{\n any::Any,\n cell::RefCell,\n future::Future,\n panic::{catch_unwind, AssertUnwindSafe},\n pin::Pin,\n sync::{\n atomic::{AtomicUsize, Ordering},\n Arc, OnceLock,\n },\n task::{ready, Context, Poll},\n thread,\n};\nuse tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit, Semaphore};\n\n/// RPC Tracing call guard semaphore.\n///\n/// This is used to restrict the number of concurrent RPC requests to tracing methods like\n/// `debug_traceTransaction` as well as `eth_getProof` because they can consume a lot of\n/// memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) ", "middle": "{\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }", "suffix": "\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "memory and CPU.\n///\n/// This types serves as an entry guard for the [`BlockingTaskPool`] and is used to rate limit\n/// parallel blocking tasks in the pool.\n#[derive(Clone, Debug)]\npub struct BlockingTaskGuard(Arc);\n\nimpl BlockingTaskGuard {\n /// Create a new `BlockingTaskGuard` with the given maximum number of blocking tasks in\n /// parallel.\n pub fn new(max_blocking_tasks: usize) -> Self {\n Self(Arc::new(Semaphore::new(max_blocking_tasks)))\n }\n\n /// See also [`Semaphore::acquire_owned`]\n pub async fn acquire_owned(self) -> Result {\n self.0.acquire_owned().await\n }\n\n /// See also [`Semaphore::acquire_many_owned`]\n pub async fn acquire_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n", "middle": " pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n", "suffix": "\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| ", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) ", "middle": "{\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }", "suffix": "\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type chec", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "el dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n", "middle": " pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n", "suffix": "\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n ", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "_many_owned(self, n: u32) -> Result {\n self.0.acquire_many_owned(n).await\n }\n}\n\n/// Used to execute blocking tasks on a rayon threadpool from within a tokio runtime.\n///\n/// This is a dedicated threadpool for blocking tasks which are CPU bound.\n/// RPC calls that perform blocking IO (disk lookups) are not executed on this pool but on the tokio\n/// runtime's blocking pool, which performs poorly with CPU bound tasks (see\n/// ). Once the tokio blocking\n/// pool is saturated it is converted into a queue, blocking tasks could then interfere with the\n/// queue and block other RPC calls.\n///\n/// See also [tokio-docs] for more information.\n///\n/// [tokio-docs]: https://docs.rs/tokio/latest/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) ", "middle": "{\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }", "suffix": "\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n", "middle": " pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n", "suffix": "\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was prev", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "he same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R ", "middle": "{\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }", "suffix": "\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different ty", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "t/tokio/index.html#cpu-bound-tasks-and-blocking-code\n#[derive(Clone, Debug)]\npub struct BlockingTaskPool {\n pool: Arc,\n}\n\nimpl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n", "middle": " pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n", "suffix": "\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R ", "middle": "{\n self.pool().install(f)\n }", "suffix": "\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "impl BlockingTaskPool {\n /// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n", "middle": " pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n", "suffix": "\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "// Create a new `BlockingTaskPool` with the given threadpool.\n pub fn new(pool: rayon::ThreadPool) -> Self {\n Self { pool: Arc::new(pool) }\n }\n\n /// Convenience function to start building a new threadpool.\n pub fn builder() -> rayon::ThreadPoolBuilder {\n rayon::ThreadPoolBuilder::new()\n }\n\n /// Convenience function to build a new threadpool with the default configuration.\n ///\n /// Uses [`rayon::ThreadPoolBuilder::build`](rayon::ThreadPoolBuilder::build) defaults.\n /// If a different stack size or other parameters are needed, they can be configured via\n /// [`rayon::ThreadPoolBuilder`] returned by [`Self::builder`].\n pub fn build() -> Result {\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) ", "middle": "{\n self.pool().spawn(f);\n }", "suffix": "\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "ting it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n", "middle": " pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n", "suffix": "\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> ", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R ", "middle": "{\n self.pool().in_place_scope(f)\n }", "suffix": "\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n ", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "{\n Self::builder().build().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n", "middle": " pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n", "suffix": "\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "d().map(Self::new)\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn`](rayon::ThreadPool::spawn).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n\n /// Asynchronous wrapper around Rayon's\n /// [`ThreadPool::spawn_fifo`](rayon::ThreadPool::spawn_fifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R ", "middle": "{\n WORKER.with_borrow(|worker| f(worker))\n }", "suffix": "\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n", "middle": " pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n", "suffix": "}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\")", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R ", "middle": "{\n WORKER.with_borrow_mut(|worker| f(worker))\n }", "suffix": "\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |work", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "t(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\n", "middle": "pub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n", "suffix": "\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "nit::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result ", "middle": "{\n builder.panic_handler(|_| {}).build()\n}", "suffix": "\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "ifo).\n ///\n /// Runs a function on the configured threadpool, returning a future that resolves with the\n /// function's return value.\n ///\n /// If the function panics, the future will resolve to an error.\n pub fn spawn_fifo(&self, func: F) -> BlockingTaskHandle\n where\n F: FnOnce() -> R + Send + 'static,\n R: Send + 'static,\n {\n let (tx, rx) = oneshot::channel();\n\n self.pool.spawn_fifo(move || {\n let _result = tx.send(catch_unwind(AssertUnwindSafe(func)));\n });\n\n BlockingTaskHandle { rx }\n }\n}\n\n/// Async handle for a blocking task running in a Rayon thread pool.\n///\n/// ## Panics\n///\n/// If polled from outside a tokio runtime.\n#[derive(Debug)]\n#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n", "middle": "/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n", "suffix": "\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n", "middle": " const fn new() -> Self {\n Self { state: None }\n }\n", "suffix": "\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *work", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self ", "middle": "{\n Self { state: None }\n }", "suffix": "\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n", "middle": " pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n", "suffix": "\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |work", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "= \"futures do nothing unless you `.await` or poll them\"]\n#[pin_project::pin_project]\npub struct BlockingTaskHandle {\n #[pin]\n pub(crate) rx: oneshot::Receiver>,\n}\n\nimpl Future for BlockingTaskHandle {\n type Output = thread::Result;\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n match ready!(self.project().rx.poll(cx)) {\n Ok(res) => Poll::Ready(res),\n Err(_) => Poll::Ready(Err(Box::::default())),\n }\n }\n}\n\n/// An error returned when the Tokio channel is dropped while awaiting a result.\n///\n/// This should only happen\n#[derive(Debug, Default, thiserror::Error)]\n#[error(\"tokio channel dropped while awaiting result\")]\n#[non_exhaustive]\npub struct TokioBlockingTaskError;\n\nthread_local! {\n static WORKER: RefCell = const { RefCell::new(Worker::new()) };\n}\n\n/// A rayon thread pool with per-thread [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) ", "middle": "{\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }", "suffix": "\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n", "middle": " pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n", "suffix": "\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "KER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T ", "middle": "{\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }", "suffix": "\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n", "middle": " pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n", "suffix": "\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " [`Worker`] state.\n///\n/// Each thread in the pool has its own [`Worker`] that can hold arbitrary state via\n/// [`Worker::init`]. The state is thread-local and accessible during [`install`](Self::install)\n/// calls.\n///\n/// The pool supports multiple init/clear cycles, allowing reuse of the same threads with\n/// different state configurations.\n///\n/// The underlying rayon pool is created lazily on first access.\n#[derive(Debug)]\npub struct WorkerPool {\n pool: OnceLock,\n num_threads: usize,\n thread_name_prefix: &'static str,\n}\n\nimpl WorkerPool {\n /// Creates a new lazy `WorkerPool` with the given number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T ", "middle": "{\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }", "suffix": "\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "e [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n", "middle": " pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n", "suffix": "\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "osures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T ", "middle": "{\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }", "suffix": "\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "iven number of threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n", "middle": " pub fn clear(&mut self) {\n self.state = None;\n }\n", "suffix": "}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "f threads and a thread name prefix.\n ///\n /// The underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) ", "middle": "{\n self.state = None;\n }", "suffix": "\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " underlying rayon pool is not created until the first method that requires it is called.\n /// Thread names follow the pattern `\"{prefix}-{index:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::*;\n", "suffix": "\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n", "middle": " async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n", "suffix": "\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "dex:02}\"`.\n pub const fn new(num_threads: usize, thread_name_prefix: &'static str) -> Self {\n Self { pool: OnceLock::new(), num_threads, thread_name_prefix }\n }\n\n /// Returns a reference to the underlying rayon pool, creating it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() ", "middle": "{\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }", "suffix": "\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "e(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n", "middle": " async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n", "suffix": "\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " it on first access.\n fn pool(&self) -> &rayon::ThreadPool {\n self.pool.get_or_init(|| {\n let prefix = self.thread_name_prefix;\n build_pool_with_panic_handler(\n rayon::ThreadPoolBuilder::new()\n .num_threads(self.num_threads)\n .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() ", "middle": "{\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }", "suffix": "\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " .thread_name(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n", "middle": " fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n", "suffix": "\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "(move |i| format!(\"{prefix}-{i:02}\")),\n )\n .unwrap_or_else(|err| panic!(\"failed to build {prefix} worker pool: {err}\"))\n })\n }\n\n /// Returns `true` if the underlying rayon pool has been initialized.\n pub fn is_initialized(&self) -> bool {\n self.pool.get().is_some()\n }\n\n /// Returns the total number of threads in the underlying rayon pool.\n pub fn current_num_threads(&self) -> usize {\n self.pool().current_num_threads()\n }\n\n /// Initializes per-thread [`Worker`] state on every thread in the pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() ", "middle": "{\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }", "suffix": "\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": " itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n", "middle": " fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n", "suffix": "\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "pool.\n pub fn init(&self, f: impl Fn(Option<&mut T>) -> T + Sync) {\n self.broadcast(self.pool().current_num_threads(), |worker| {\n worker.init::(&f);\n });\n }\n\n /// Runs a closure on `num_threads` threads in the pool, giving mutable access to each\n /// thread's [`Worker`].\n ///\n /// Use this to initialize or re-initialize per-thread state via [`Worker::init`].\n /// Only `num_threads` threads execute the closure; the rest skip it.\n pub fn broadcast(&self, num_threads: usize, f: impl Fn(&mut Worker) + Sync) {\n if num_threads >= self.pool().current_num_threads() {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() ", "middle": "{\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }", "suffix": "\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "lizes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n", "middle": " fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n", "suffix": "\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": ") {\n // Fast path: run on every thread, no atomic coordination needed.\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n } else {\n let remaining = AtomicUsize::new(num_threads);\n self.pool().broadcast(|_| {\n // Atomically claim a slot; threads that can't decrement skip the closure.\n let mut current = remaining.load(Ordering::Relaxed);\n loop {\n if current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() ", "middle": "{\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }", "suffix": "\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "current == 0 {\n return;\n }\n match remaining.compare_exchange_weak(\n current,\n current - 1,\n Ordering::Relaxed,\n Ordering::Relaxed,\n ) {\n Ok(_) => break,\n Err(actual) => current = actual,\n }\n }\n WORKER.with_borrow_mut(|worker| f(worker));\n });\n }\n }\n\n /// Clears the state on every thread in the pool.\n pub fn clear(&self) {\n self.pool().broadcast(|_| {\n WORKER.with_borrow_mut(Worker::clear);\n });\n }\n\n /// Runs a closure on the pool with access to the calling thread's [`Worker`].\n ///\n /// All rayon parallelism (e.g. `par_iter`) spawned inside the closure executes on this pool.\n /// Each thread can access its own [`Worker`] via the provided reference or through additional\n /// [`WorkerPool::with_worker`] calls.\n pub fn install(&self, f: impl FnOnce(&Worker) -> R + Send) -> R {\n self.pool().install(|| WORKER.with_borrow(|worker| f(worker)))\n }\n\n /// Runs a closure on the pool without worker state access.\n ///\n /// Like [`install`](Self::install) but for closures that don't need per-thread [`Worker`]\n /// state.\n pub fn install_fn(&self, f: impl FnOnce() -> R + Send) -> R {\n self.pool().install(f)\n }\n\n /// Spawns a closure on the pool.\n pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {\n self.pool().spawn(f);\n }\n\n /// Executes `f` on this pool using [`rayon::in_place_scope`], which converts the calling\n /// thread into a worker for the duration \u2014 tasks spawned inside the scope run on the pool\n /// and the call blocks until all of them complete.\n pub fn in_place_scope<'scope, R>(&self, f: impl FnOnce(&rayon::Scope<'scope>) -> R) -> R {\n self.pool().in_place_scope(f)\n }\n\n /// Access the current thread's [`Worker`] from within an [`install`](Self::install) closure.\n ///\n /// This is useful for accessing the worker from inside `par_iter` where the initial `&Worker`\n /// reference from `install` belongs to a different thread.\n pub fn with_worker(f: impl FnOnce(&Worker) -> R) -> R {\n WORKER.with_borrow(|worker| f(worker))\n }\n\n /// Mutably access the current thread's [`Worker`] from within a pool closure.\n pub fn with_worker_mut(f: impl FnOnce(&mut Worker) -> R) -> R {\n WORKER.with_borrow_mut(|worker| f(worker))\n }\n}\n\n/// Builds a rayon thread pool with a panic handler that prevents aborting the process.\n///\n/// Rust's default panic hook already logs the panic message and backtrace to stderr, so the handler\n/// itself is intentionally a no-op.\npub fn build_pool_with_panic_handler(\n builder: rayon::ThreadPoolBuilder,\n) -> Result {\n builder.panic_handler(|_| {}).build()\n}\n\n/// Per-thread state container for a [`WorkerPool`].\n///\n/// Holds a type-erased `Box` that can be initialized and accessed with concrete types\n/// via [`init`](Self::init) and [`get`](Self::get).\n#[derive(Debug, Default)]\npub struct Worker {\n state: Option>,\n}\n\nimpl Worker {\n /// Creates a new empty `Worker`.\n const fn new() -> Self {\n Self { state: None }\n }\n\n /// Initializes the worker state.\n ///\n /// If state of type `T` already exists, passes `Some(&mut T)` to the closure so resources\n /// can be reused. On first init, passes `None`.\n pub fn init(&mut self, f: impl FnOnce(Option<&mut T>) -> T) {\n let existing =\n self.state.take().and_then(|mut b| b.downcast_mut::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n", "middle": " fn worker_pool_par_iter_with_worker() {\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/tasks/src/pool.rs", "prefix": ");\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() ", "middle": "{\n use rayon::prelude::*;\n\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/tasks/src/pool.rs", "prefix": "::().is_some().then_some(b));\n\n let new_state = match existing {\n Some(mut boxed) => {\n let r = boxed.downcast_mut::().expect(\"type checked above\");\n *r = f(Some(r));\n boxed\n }\n None => Box::new(f(None)),\n };\n\n self.state = Some(new_state);\n }\n\n /// Returns a reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get(&self) -> &T {\n self.state\n .as_ref()\n .expect(\"worker not initialized\")\n .downcast_ref::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, downcasted to `T`.\n ///\n /// # Panics\n ///\n /// Panics if the worker has not been initialized or if the type does not match.\n pub fn get_mut(&mut self) -> &mut T {\n self.state\n .as_mut()\n .expect(\"worker not initialized\")\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Returns a mutable reference to the state, initializing it with `f` on first access.\n ///\n /// # Panics\n ///\n /// Panics if the state was previously initialized with a different type.\n pub fn get_or_init(&mut self, f: impl FnOnce() -> T) -> &mut T {\n self.state\n .get_or_insert_with(|| Box::new(f()))\n .downcast_mut::()\n .expect(\"worker state type mismatch\")\n }\n\n /// Clears the worker state, dropping the contained value.\n pub fn clear(&mut self) {\n self.state = None;\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[tokio::test]\n async fn blocking_pool() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || 5);\n let res = res.await.unwrap();\n assert_eq!(res, 5);\n }\n\n #[tokio::test]\n async fn blocking_pool_panic() {\n let pool = BlockingTaskPool::build().unwrap();\n let res = pool.spawn(move || -> i32 {\n panic!();\n });\n let res = res.await;\n assert!(res.is_err());\n }\n\n #[test]\n fn worker_pool_init_and_access() {\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::>(|_| vec![1, 2, 3]);\n });\n\n let sum: u8 = pool.install(|worker| {\n let v = worker.get::>();\n v.iter().sum()\n });\n assert_eq!(sum, 6);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_reinit_reuses_resources() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n assert!(existing.is_none());\n vec![1, 2, 3]\n });\n });\n\n pool.broadcast(1, |worker| {\n worker.init::>(|existing| {\n let v = existing.expect(\"should have existing state\");\n assert_eq!(v, &mut vec![1, 2, 3]);\n v.push(4);\n std::mem::take(v)\n });\n });\n\n let len = pool.install(|worker| worker.get::>().len());\n assert_eq!(len, 4);\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_clear_and_reinit() {\n let pool = WorkerPool::new(1, \"test\");\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| 42);\n });\n let val = pool.install(|worker| *worker.get::());\n assert_eq!(val, 42);\n\n pool.clear();\n\n pool.broadcast(1, |worker| {\n worker.init::(|_| \"hello\".to_string());\n });\n let val = pool.install(|worker| worker.get::().clone());\n assert_eq!(val, \"hello\");\n\n pool.clear();\n }\n\n #[test]\n fn worker_pool_par_iter_with_worker() {\n", "middle": " use rayon::prelude::*;\n", "suffix": "\n let pool = WorkerPool::new(2, \"test\");\n\n pool.broadcast(2, |worker| {\n worker.init::(|_| 10);\n });\n\n let results: Vec = pool.install(|_| {\n (0u64..4)\n .into_par_iter()\n .map(|i| WorkerPool::with_worker(|w| i + *w.get::()))\n .collect()\n });\n assert_eq!(results, vec![10, 11, 12, 13]);\n\n pool.clear();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\n", "middle": "use futures::{ready, Stream, StreamExt};\n", "suffix": "use std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n ", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\n", "middle": "use std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\n", "suffix": "use tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\n", "middle": "use tokio::net::{TcpListener, TcpStream};\n", "suffix": "\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n", "middle": "/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n", "suffix": "\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n", "middle": " pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n", "suffix": "\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result ", "middle": "{\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }", "suffix": "\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n", "middle": " pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n", "suffix": "\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self ", "middle": "{\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }", "suffix": "\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n", "middle": " pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n", "suffix": "}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr ", "middle": "{\n self.local_address\n }", "suffix": "\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n", "middle": "/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n", "suffix": "\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n", "middle": " fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n", "suffix": "}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> ", "middle": "{\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }", "suffix": "\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::*;\n", "suffix": " use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n", "middle": " use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n", "suffix": " use tokio::macros::support::poll_fn;\n\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/listener.rs", "prefix": "//! Contains connection-oriented interfaces.\n\nuse futures::{ready, Stream, StreamExt};\nuse std::{\n io,\n net::SocketAddr,\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::net::{TcpListener, TcpStream};\n\n/// A tcp connection listener.\n///\n/// Listens for incoming connections.\n#[must_use = \"Transport does nothing unless polled.\"]\n#[derive(Debug)]\npub struct ConnectionListener {\n /// Local address of the listener stream.\n local_address: SocketAddr,\n /// The active tcp listener for incoming connections.\n incoming: TcpListenerStream,\n}\n\nimpl ConnectionListener {\n /// Creates a new [`TcpListener`] that listens for incoming connections.\n pub async fn bind(addr: SocketAddr) -> io::Result {\n let listener = TcpListener::bind(addr).await?;\n let local_addr = listener.local_addr()?;\n Ok(Self::new(listener, local_addr))\n }\n\n /// Creates a new connection listener stream.\n pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self {\n Self { local_address, incoming: TcpListenerStream { inner: listener } }\n }\n\n /// Polls the type to make progress.\n pub fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n match ready!(this.incoming.poll_next_unpin(cx)) {\n Some(Ok((stream, remote_addr))) => {\n if let Err(err) = stream.set_nodelay(true) {\n tracing::warn!(target: \"net\", \"set nodelay failed: {:?}\", err);\n }\n Poll::Ready(ListenerEvent::Incoming { stream, remote_addr })\n }\n Some(Err(err)) => Poll::Ready(ListenerEvent::Error(err)),\n None => {\n Poll::Ready(ListenerEvent::ListenerClosed { local_address: this.local_address })\n }\n }\n }\n\n /// Returns the socket address this listener listens on.\n pub const fn local_address(&self) -> SocketAddr {\n self.local_address\n }\n}\n\n/// Event type produced by the [`TcpListenerStream`].\npub enum ListenerEvent {\n /// Received a new incoming.\n Incoming {\n /// Accepted connection\n stream: TcpStream,\n /// Address of the remote peer.\n remote_addr: SocketAddr,\n },\n /// Returned when the underlying connection listener has been closed.\n ///\n /// This is the case if the [`TcpListenerStream`] should ever return `None`\n ListenerClosed {\n /// Address of the closed listener.\n local_address: SocketAddr,\n },\n /// Encountered an error when accepting a connection.\n ///\n /// This is a non-fatal error as the listener continues to listen for new connections to\n /// accept.\n Error(io::Error),\n}\n\n/// A stream of incoming [`TcpStream`]s.\n#[derive(Debug)]\nstruct TcpListenerStream {\n /// listener for incoming connections.\n inner: TcpListener,\n}\n\nimpl Stream for TcpListenerStream {\n type Item = io::Result<(TcpStream, SocketAddr)>;\n\n fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> {\n match self.inner.poll_accept(cx) {\n Poll::Ready(Ok(conn)) => Poll::Ready(Some(Ok(conn))),\n Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),\n Poll::Pending => Poll::Pending,\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::{\n net::{Ipv4Addr, SocketAddrV4},\n pin::pin,\n };\n", "middle": " use tokio::macros::support::poll_fn;\n", "suffix": "\n #[tokio::test(flavor = \"multi_thread\")]\n async fn test_incoming_listener() {\n let listener =\n ConnectionListener::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .await\n .unwrap();\n let local_addr = listener.local_address();\n\n tokio::task::spawn(async move {\n let mut listener = pin!(listener);\n match poll_fn(|cx| listener.as_mut().poll(cx)).await {\n ListenerEvent::Incoming { .. } => {}\n _ => {\n panic!(\"unexpected event\")\n }\n }\n });\n\n let _ = TcpStream::connect(local_addr).await.unwrap();\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\n", "middle": "use crate::alloc::string::ToString;\n", "suffix": "use alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n ", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\n", "middle": "use alloc::string::String;\n", "suffix": "use alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.ha", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\n", "middle": "use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n", "suffix": "use bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// ", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\n", "middle": "use bytes::BufMut;\n", "suffix": "use core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\n", "middle": "use core::{fmt, str::FromStr};\n", "suffix": "use derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\n", "middle": "use derive_more::Display;\n", "suffix": "use reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion:", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\n", "middle": "use reth_codecs_derive::add_arbitrary_tests;\n", "suffix": "\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n", "middle": "/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n", "suffix": "\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n", "nodeType": "Struct"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n", "middle": "/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n", "suffix": "\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n ", "nodeType": "Enum"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n", "middle": " pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n", "suffix": "\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth66)\n }", "suffix": "\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n", "middle": " pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n", "suffix": "\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deseriali", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth67)\n }", "suffix": "\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n", "middle": " pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n", "suffix": "\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersi", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth68)\n }", "suffix": "\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n", "middle": " pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n", "suffix": "\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }", "suffix": "\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self a", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n", "middle": " pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n", "suffix": "\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n ", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth69)\n }", "suffix": "\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) ->", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n", "middle": " pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n", "suffix": "\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable f", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth70)\n }", "suffix": "\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n", "middle": " pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n", "suffix": "\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n mat", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth71)\n }", "suffix": "\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n", "middle": " pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n", "suffix": "\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth72)\n }", "suffix": "\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n", "middle": " pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n", "suffix": "}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::Byte", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool ", "middle": "{\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }", "suffix": "\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n", "middle": "/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n", "suffix": "\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_fro", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n", "middle": " fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n", "suffix": "\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) ", "middle": "{\n (*self as u8).encode(out)\n }", "suffix": "\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n as", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n", "middle": " fn length(&self) -> usize {\n (*self as u8).length()\n }\n", "suffix": "}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").un", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize ", "middle": "{\n (*self as u8).length()\n }", "suffix": "\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n", "middle": "/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n", "suffix": "\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n", "middle": " fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n", "suffix": "}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result ", "middle": "{\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }", "suffix": "\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\"", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n", "middle": "/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n", "suffix": "\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n", "middle": " fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n", "suffix": "}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result ", "middle": "{\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }", "suffix": "\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n", "middle": "/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n", "suffix": "\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n", "middle": " fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n", "suffix": "}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n ", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": ")]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result ", "middle": "{\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }", "suffix": "\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = Byte", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\n", "middle": "impl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n", "suffix": "\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "/ The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n", "middle": " fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n", "suffix": "}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n ", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "on 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result ", "middle": "{\n Self::try_from(s)\n }", "suffix": "\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\n", "middle": "impl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n", "suffix": "\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8,", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n", "middle": " fn from(v: EthVersion) -> Self {\n v as Self\n }\n", "suffix": "}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self ", "middle": "{\n v as Self\n }", "suffix": "\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\n", "middle": "impl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n", "suffix": "\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expe", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n", "middle": " fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n", "suffix": "}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "b const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str ", "middle": "{\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }", "suffix": "\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encod", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": ")\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n", "middle": "/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n", "suffix": "\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Enum"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": ") -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\n", "middle": "impl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n", "suffix": "\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n", "middle": " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n", "suffix": "}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result ", "middle": "{\n write!(f, \"v{}\", *self as u8)\n }", "suffix": "\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\n", "middle": "impl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n", "suffix": "\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n", "middle": " fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n", "suffix": " fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) ", "middle": "{\n (*self as u8).encode(out)\n }", "suffix": "\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n", "middle": " fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n", "suffix": "}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize ", "middle": "{\n // the version should be a single byte\n (*self as u8).length()\n }", "suffix": "\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "atches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\n", "middle": "impl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n", "suffix": "\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n", "middle": " fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n", "suffix": "}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "rns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result ", "middle": "{\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }", "suffix": "\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::EthVersion;\n", "suffix": " use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "s_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n", "middle": " use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n", "suffix": " use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "tches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n", "middle": " use bytes::BytesMut;\n", "suffix": "\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n", "middle": " fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n", "suffix": "\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "des a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() ", "middle": "{\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }", "suffix": "\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n", "middle": " fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n", "suffix": "\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "//! Support for representing the version of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() ", "middle": "{\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }", "suffix": "\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n", "middle": " fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n", "suffix": "\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "of the `eth`\n\nuse crate::alloc::string::ToString;\nuse alloc::string::String;\nuse alloy_rlp::{Decodable, Encodable, Error as RlpError};\nuse bytes::BufMut;\nuse core::{fmt, str::FromStr};\nuse derive_more::Display;\nuse reth_codecs_derive::add_arbitrary_tests;\n\n/// Error thrown when failed to parse a valid [`EthVersion`].\n#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]\n#[error(\"Unknown eth protocol version: {0}\")]\npub struct ParseVersionError(String);\n\n/// The `eth` protocol version.\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() ", "middle": "{\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }", "suffix": "\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "=> Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n", "middle": " fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n", "suffix": " #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": "(u8)]\n#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Display)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\npub enum EthVersion {\n /// The `eth` protocol version 66.\n Eth66 = 66,\n /// The `eth` protocol version 67.\n Eth67 = 67,\n /// The `eth` protocol version 68.\n Eth68 = 68,\n /// The `eth` protocol version 69.\n Eth69 = 69,\n /// The `eth` protocol version 70.\n Eth70 = 70,\n /// The `eth` protocol version 71.\n Eth71 = 71,\n /// The `eth` protocol version 72.\n Eth72 = 72,\n}\n\nimpl EthVersion {\n /// The latest known eth version\n pub const LATEST: Self = Self::Eth69;\n\n /// All known eth versions\n pub const ALL_VERSIONS: &'static [Self] = &[Self::Eth69, Self::Eth68, Self::Eth67, Self::Eth66];\n\n /// Returns true if the version is eth/66\n pub const fn is_eth66(&self) -> bool {\n matches!(self, Self::Eth66)\n }\n\n /// Returns true if the version is eth/67\n pub const fn is_eth67(&self) -> bool {\n matches!(self, Self::Eth67)\n }\n\n /// Returns true if the version is eth/68\n pub const fn is_eth68(&self) -> bool {\n matches!(self, Self::Eth68)\n }\n\n /// Returns true if the version carries eth/68 transaction announcement metadata.\n pub const fn has_eth68_metadata(&self) -> bool {\n matches!(self, Self::Eth68 | Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n\n /// Returns true if the version is eth/69\n pub const fn is_eth69(&self) -> bool {\n matches!(self, Self::Eth69)\n }\n\n /// Returns true if the version is eth/70\n pub const fn is_eth70(&self) -> bool {\n matches!(self, Self::Eth70)\n }\n\n /// Returns true if the version is eth/71\n pub const fn is_eth71(&self) -> bool {\n matches!(self, Self::Eth71)\n }\n\n /// Returns true if the version is eth/72\n pub const fn is_eth72(&self) -> bool {\n matches!(self, Self::Eth72)\n }\n\n /// Returns true if the version is eth/69 or newer.\n pub const fn is_eth69_or_newer(&self) -> bool {\n matches!(self, Self::Eth69 | Self::Eth70 | Self::Eth71 | Self::Eth72)\n }\n}\n\n/// RLP encodes `EthVersion` as a single byte (66-71).\nimpl Encodable for EthVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n\n fn length(&self) -> usize {\n (*self as u8).length()\n }\n}\n\n/// RLP decodes a single byte into `EthVersion`.\n/// Returns error if byte is not a valid version (66-71).\nimpl Decodable for EthVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n Self::try_from(version).map_err(|_| RlpError::Custom(\"invalid eth version\"))\n }\n}\n\n/// Allow for converting from a `&str` to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(\"67\").unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom<&str> for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(s: &str) -> Result {\n match s {\n \"66\" => Ok(Self::Eth66),\n \"67\" => Ok(Self::Eth67),\n \"68\" => Ok(Self::Eth68),\n \"69\" => Ok(Self::Eth69),\n \"70\" => Ok(Self::Eth70),\n \"71\" => Ok(Self::Eth71),\n \"72\" => Ok(Self::Eth72),\n _ => Err(ParseVersionError(s.to_string())),\n }\n }\n}\n\n/// Allow for converting from a u8 to an `EthVersion`.\n///\n/// # Example\n/// ```\n/// use reth_eth_wire_types::EthVersion;\n///\n/// let version = EthVersion::try_from(67).unwrap();\n/// assert_eq!(version, EthVersion::Eth67);\n/// ```\nimpl TryFrom for EthVersion {\n type Error = ParseVersionError;\n\n #[inline]\n fn try_from(u: u8) -> Result {\n match u {\n 66 => Ok(Self::Eth66),\n 67 => Ok(Self::Eth67),\n 68 => Ok(Self::Eth68),\n 69 => Ok(Self::Eth69),\n 70 => Ok(Self::Eth70),\n 71 => Ok(Self::Eth71),\n 72 => Ok(Self::Eth72),\n _ => Err(ParseVersionError(u.to_string())),\n }\n }\n}\n\nimpl FromStr for EthVersion {\n type Err = ParseVersionError;\n\n #[inline]\n fn from_str(s: &str) -> Result {\n Self::try_from(s)\n }\n}\n\nimpl From for u8 {\n #[inline]\n fn from(v: EthVersion) -> Self {\n v as Self\n }\n}\n\nimpl From for &'static str {\n #[inline]\n fn from(v: EthVersion) -> &'static str {\n match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() ", "middle": "{\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }", "suffix": "\n #[test]\n fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " match v {\n EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n", "middle": " fn test_eth_version_rlp_decode() {\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/net/eth-wire-types/src/version.rs", "prefix": " EthVersion::Eth66 => \"66\",\n EthVersion::Eth67 => \"67\",\n EthVersion::Eth68 => \"68\",\n EthVersion::Eth69 => \"69\",\n EthVersion::Eth70 => \"70\",\n EthVersion::Eth71 => \"71\",\n EthVersion::Eth72 => \"72\",\n }\n }\n}\n\n/// `RLPx` `p2p` protocol version\n#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]\n#[cfg_attr(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]\n#[cfg_attr(any(test, feature = \"arbitrary\"), derive(arbitrary::Arbitrary))]\n#[add_arbitrary_tests(rlp)]\npub enum ProtocolVersion {\n /// `p2p` version 4\n V4 = 4,\n /// `p2p` version 5\n #[default]\n V5 = 5,\n}\n\nimpl fmt::Display for ProtocolVersion {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"v{}\", *self as u8)\n }\n}\n\nimpl Encodable for ProtocolVersion {\n fn encode(&self, out: &mut dyn BufMut) {\n (*self as u8).encode(out)\n }\n fn length(&self) -> usize {\n // the version should be a single byte\n (*self as u8).length()\n }\n}\n\nimpl Decodable for ProtocolVersion {\n fn decode(buf: &mut &[u8]) -> alloy_rlp::Result {\n let version = u8::decode(buf)?;\n match version {\n 4 => Ok(Self::V4),\n 5 => Ok(Self::V5),\n _ => Err(RlpError::Custom(\"unknown p2p protocol version\")),\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::EthVersion;\n use alloy_rlp::{Decodable, Encodable, Error as RlpError};\n use bytes::BytesMut;\n\n #[test]\n fn test_eth_version_try_from_str() {\n assert_eq!(EthVersion::Eth66, EthVersion::try_from(\"66\").unwrap());\n assert_eq!(EthVersion::Eth67, EthVersion::try_from(\"67\").unwrap());\n assert_eq!(EthVersion::Eth68, EthVersion::try_from(\"68\").unwrap());\n assert_eq!(EthVersion::Eth69, EthVersion::try_from(\"69\").unwrap());\n assert_eq!(EthVersion::Eth70, EthVersion::try_from(\"70\").unwrap());\n assert_eq!(EthVersion::Eth71, EthVersion::try_from(\"71\").unwrap());\n assert_eq!(EthVersion::Eth72, EthVersion::try_from(\"72\").unwrap());\n }\n\n #[test]\n fn test_eth_version_from_str() {\n assert_eq!(EthVersion::Eth66, \"66\".parse().unwrap());\n assert_eq!(EthVersion::Eth67, \"67\".parse().unwrap());\n assert_eq!(EthVersion::Eth68, \"68\".parse().unwrap());\n assert_eq!(EthVersion::Eth69, \"69\".parse().unwrap());\n assert_eq!(EthVersion::Eth70, \"70\".parse().unwrap());\n assert_eq!(EthVersion::Eth71, \"71\".parse().unwrap());\n assert_eq!(EthVersion::Eth72, \"72\".parse().unwrap());\n }\n\n #[test]\n fn test_has_eth68_metadata() {\n assert!(!EthVersion::Eth66.has_eth68_metadata());\n assert!(!EthVersion::Eth67.has_eth68_metadata());\n assert!(EthVersion::Eth68.has_eth68_metadata());\n assert!(EthVersion::Eth69.has_eth68_metadata());\n assert!(EthVersion::Eth70.has_eth68_metadata());\n assert!(EthVersion::Eth71.has_eth68_metadata());\n assert!(EthVersion::Eth72.has_eth68_metadata());\n }\n\n #[test]\n fn test_eth_version_rlp_encode() {\n let versions = [\n EthVersion::Eth66,\n EthVersion::Eth67,\n EthVersion::Eth68,\n EthVersion::Eth69,\n EthVersion::Eth70,\n EthVersion::Eth71,\n EthVersion::Eth72,\n ];\n\n for version in versions {\n let mut encoded = BytesMut::new();\n version.encode(&mut encoded);\n\n assert_eq!(encoded.len(), 1);\n assert_eq!(encoded[0], version as u8);\n }\n }\n #[test]\n fn test_eth_version_rlp_decode() ", "middle": "{\n let test_cases = [\n (66_u8, Ok(EthVersion::Eth66)),\n (67_u8, Ok(EthVersion::Eth67)),\n (68_u8, Ok(EthVersion::Eth68)),\n (69_u8, Ok(EthVersion::Eth69)),\n (70_u8, Ok(EthVersion::Eth70)),\n (71_u8, Ok(EthVersion::Eth71)),\n (72_u8, Ok(EthVersion::Eth72)),\n (65_u8, Err(RlpError::Custom(\"invalid eth version\"))),\n ];\n\n for (input, expected) in test_cases {\n let mut encoded = BytesMut::new();\n input.encode(&mut encoded);\n\n let mut slice = encoded.as_ref();\n let result = EthVersion::decode(&mut slice);\n assert_eq!(result, expected);\n }\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/stages/api/src/pipeline/progress.rs", "prefix": "", "middle": "use crate::{util::opt, ControlFlow};\n", "suffix": "use alloy_primitives::BlockNumber;\n\n#[derive(Debug, Default)]\npub(crate) struct PipelineProgress {\n /// Block number reached by the stage.\n pub(crate) block_number: Option,\n /// The maximum block number achieved by any stage during the execution of the pipeline.\n pub(crate) maximum_block_number: Option,\n /// The minimum block number achieved by any stage during the execution of the pipeline.\n pub(crate) minimum_block_number: Option,\n}\n\nimpl PipelineProgress {\n pub(crate) fn update(&mut self, block_number: BlockNumber) {\n self.block_number = Some(block_number);\n self.minimum_block_number = opt::min(self.minimum_block_number, block_number);\n self.maximum_block_number = opt::max(self.maximum_block_number, block_number);\n }\n\n /// Get next control flow step\n pub(crate) const fn next_ctrl(&self) -> ControlFlow {\n match self.block_number {\n Some(block_number) => ControlFlow::Continue { block_number },\n None => ControlFlow::NoProgress { block_number: None },\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/stages/api/src/pipeline/progress.rs", "prefix": "use crate::{util::opt, ControlFlow};\n", "middle": "use alloy_primitives::BlockNumber;\n", "suffix": "\n#[derive(Debug, Default)]\npub(crate) struct PipelineProgress {\n /// Block number reached by the stage.\n pub(crate) block_number: Option,\n /// The maximum block number achieved by any stage during the execution of the pipeline.\n pub(crate) maximum_block_number: Option,\n /// The minimum block number achieved by any stage during the execution of the pipeline.\n pub(crate) minimum_block_number: Option,\n}\n\nimpl PipelineProgress {\n pub(crate) fn update(&mut self, block_number: BlockNumber) {\n self.block_number = Some(block_number);\n self.minimum_block_number = opt::min(self.minimum_block_number, block_number);\n self.maximum_block_number = opt::max(self.maximum_block_number, block_number);\n }\n\n /// Get next control flow step\n pub(crate) const fn next_ctrl(&self) -> ControlFlow {\n match self.block_number {\n Some(block_number) => ControlFlow::Continue { block_number },\n None => ControlFlow::NoProgress { block_number: None },\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/exex/exex/src/backfill/mod.rs", "prefix": "", "middle": "mod factory;\n", "suffix": "mod job;\nmod stream;\n#[cfg(test)]\nmod test_utils;\n\npub use factory::BackfillJobFactory;\npub use job::{BackfillJob, SingleBlockBackfillJob};\npub use stream::StreamBackfillJob;\n", "nodeType": "Mod"} {"filePath": "crates/exex/exex/src/backfill/mod.rs", "prefix": "mod factory;\nmod job;\n", "middle": "mod stream;\n", "suffix": "#[cfg(test)]\nmod test_utils;\n\npub use factory::BackfillJobFactory;\npub use job::{BackfillJob, SingleBlockBackfillJob};\npub use stream::StreamBackfillJob;\n", "nodeType": "Mod"} {"filePath": "crates/exex/exex/src/backfill/mod.rs", "prefix": "mod factory;\nmod job;\nmod stream;\n", "middle": "#[cfg(test)]\nmod test_utils;\n", "suffix": "\npub use factory::BackfillJobFactory;\npub use job::{BackfillJob, SingleBlockBackfillJob};\npub use stream::StreamBackfillJob;\n", "nodeType": "Mod"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "", "middle": "use reth_trie_common::{Nibbles, ProofV2Target};\n", "suffix": "\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\n", "middle": "pub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n", "suffix": "\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles ", "middle": "{\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}", "suffix": "\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\n", "middle": "fn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n", "suffix": "\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &s", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option ", "middle": "{\n sub_trie_prefix.next_without_prefix()\n}", "suffix": "\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n", "middle": "/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n", "suffix": "\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\n \"4c\",\n vec![\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4", "nodeType": "Struct"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\n", "middle": "impl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n", "suffix": "\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\n \"4c\",\n vec![\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n ],\n ),\n (\n \"4e\",\n vec![\"4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e\"],\n ),\n ],\n ),\n // Case 8: Min-len 1 should result in zero-length sub-trie prefix\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(1),\n", "nodeType": "Impl"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n", "middle": " pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n", "suffix": "}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\n \"4c\",\n vec![\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n ],\n ),\n (\n \"4e\",\n vec![\"4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e\"],\n ),\n ],\n ),\n // Case 8: Min-len 1 should result in zero-length sub-trie prefix\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(1),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option ", "middle": "{\n sub_trie_upper_bound(&self.prefix)\n }", "suffix": "\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\n \"4c\",\n vec![\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n ],\n ),\n (\n \"4e\",\n vec![\"4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e\"],\n ),\n ],\n ),\n // Case 8: Min-len 1 should result in zero-length sub-trie prefix\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(1),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(1),\n ],", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::*;\n", "suffix": " use alloy_primitives::B256;\n\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/proof_v2/target.rs", "prefix": "use reth_trie_common::{Nibbles, ProofV2Target};\n\n// A helper function for getting the largest prefix of the sub-trie which contains a particular\n// target, based on its `min_len`.\n//\n// A target will only match nodes which share the target's prefix, where the target's prefix is\n// the first `min_len` nibbles of its key. E.g. a target with `key` 0xabcd and `min_len` 2 will\n// only match nodes with prefix 0xab.\n//\n// In general the target will only match within the sub-trie whose prefix is identical to the\n// target's. However there is an exception:\n//\n// Given a trie with a node at 0xabc, there must be a branch at 0xab. A target with prefix 0xabc\n// needs to match that node, but the branch at 0xab must be constructed order to know the node\n// is at that path. Therefore the sub-trie prefix is the target prefix with a nibble truncated.\n//\n// For a target with an empty prefix (`min_len` of 0) we still use an empty sub-trie prefix;\n// this will still construct the branch at the root node (if there is one). Targets with\n// `min_len` of both 0 and 1 will therefore construct the root node, but only those with\n// `min_len` of 0 will retain it.\n#[inline]\npub(crate) fn sub_trie_prefix(target: &ProofV2Target) -> Nibbles {\n let mut sub_trie_prefix = target.key_nibbles;\n sub_trie_prefix.truncate(target.min_len.saturating_sub(1) as usize);\n sub_trie_prefix\n}\n\n// A helper function which returns the first path following a sub-trie in lexicographical order.\n#[inline]\nfn sub_trie_upper_bound(sub_trie_prefix: &Nibbles) -> Option {\n sub_trie_prefix.next_without_prefix()\n}\n\n/// Describes a set of targets which all apply to a single sub-trie, ie a section of the overall\n/// trie whose nodes all share a prefix.\npub(crate) struct SubTrieTargets<'a> {\n /// The prefix which all nodes in the sub-trie share. This is also the first node in the trie\n /// in lexicographic order.\n pub(crate) prefix: Nibbles,\n /// The targets belonging to this sub-trie. These will be sorted by their `key` field,\n /// lexicographically.\n pub(crate) targets: &'a [ProofV2Target],\n /// Will be true if at least one target in the set has a zero `min_len`.\n ///\n /// If this is true then `prefix.is_empty()`, though not necessarily vice-versa.\n pub(crate) retain_root: bool,\n}\n\nimpl<'a> SubTrieTargets<'a> {\n // A helper function which returns the first path following a sub-trie in lexicographical order.\n #[inline]\n pub(crate) fn upper_bound(&self) -> Option {\n sub_trie_upper_bound(&self.prefix)\n }\n}\n\n/// Given a set of [`ProofV2Target`]s, returns an iterator over those same [`ProofV2Target`]s\n/// chunked by the sub-tries they apply to within the overall trie.\npub(crate) fn iter_sub_trie_targets(\n targets: &mut [ProofV2Target],\n) -> impl Iterator> {\n // First sort by the sub-trie prefix of each target, falling back to the `min_len` in cases\n // where the sub-trie prefixes are equal (to differentiate targets which match the root node and\n // those which don't).\n targets.sort_unstable_by(|a, b| {\n sub_trie_prefix(a).cmp(&sub_trie_prefix(b)).then_with(|| a.min_len.cmp(&b.min_len))\n });\n\n // We now chunk targets, such that each chunk contains all targets belonging to the same\n // sub-trie. We are taking advantage of the following properties:\n //\n // - The first target in the chunk has the shortest sub-trie prefix (see previous sorting step).\n //\n // - The upper bound of the first target in the chunk's sub-trie will therefore be the upper\n // bound of the whole chunk.\n // - For example, given a chunk with sub-trie prefixes [0x2, 0x2f, 0x2fa], the upper bounds\n // will be [0x3, 0x3, 0x2fb]. Note that no target could match a trie node with path equal\n // to or greater than 0x3.\n //\n // - If a target's sub-trie's prefix does not lie within the bounds of the current chunk, then\n // that target must be the first target of the next chunk, lying in a separate sub-trie.\n // - Example: given sub-trie prefixes of [0x2, 0x2fa, 0x4c, 0x4ce, 0x4e], we would end up\n // with the following chunks:\n // - [0x2, 0x2fa] w/ upper bound 0x3\n // - [0x4c 0x4ce] w/ upper bound 0x4d\n // - [0x4e] w/ upper bound 0x4f\n let mut upper_bound = targets.first().and_then(|t| sub_trie_upper_bound(&sub_trie_prefix(t)));\n let target_chunks = targets.chunk_by_mut(move |_, next| {\n if let Some(some_upper_bound) = upper_bound {\n let prefix = sub_trie_prefix(next);\n let same_chunk = prefix < some_upper_bound;\n if !same_chunk {\n upper_bound = sub_trie_upper_bound(&prefix);\n }\n same_chunk\n } else {\n true\n }\n });\n\n // Map the chunks to the return type. Within each chunk we want targets to be sorted by their\n // key, as that will be the order they are checked by the `ProofCalculator`.\n target_chunks.map(move |targets| {\n let prefix = sub_trie_prefix(&targets[0]);\n let retain_root = targets[0].min_len == 0;\n targets.sort_unstable_by_key(|target| target.key_nibbles);\n SubTrieTargets { prefix, targets, retain_root }\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n", "middle": " use alloy_primitives::B256;\n", "suffix": "\n #[test]\n fn test_iter_sub_trie_targets() {\n // Helper to create nibbles from hex string (each character is a nibble)\n let nibbles = |hex: &str| -> Nibbles {\n if hex.is_empty() {\n return Nibbles::new();\n }\n format!(\"0x{}\", hex).parse().expect(\"valid nibbles hex string\")\n };\n\n // Test cases: (input_targets, expected_output)\n // Expected output format: Vec<(exp_prefix_hex, Vec)>\n let test_cases = vec![\n // Case 1: Empty targets\n (vec![], vec![]),\n // Case 2: Single target without min_len\n (\n vec![ProofV2Target::new(B256::repeat_byte(0x20))],\n vec![(\n \"\",\n vec![\"2020202020202020202020202020202020202020202020202020202020202020\"],\n )],\n ),\n // Case 3: Multiple targets in same sub-trie (no min_len)\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)),\n ProofV2Target::new(B256::repeat_byte(0x21)),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2121212121212121212121212121212121212121212121212121212121212121\",\n ],\n )],\n ),\n // Case 4: Multiple targets in different sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\"2\", vec![\"2020202020202020202020202020202020202020202020202020202020202020\"]),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 5: Three targets, two in same sub-trie, one separate\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(2),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\"4\", vec![\"4040404040404040404040404040404040404040404040404040404040404040\"]),\n ],\n ),\n // Case 6: Targets with different min_len values in same sub-trie\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(3),\n ],\n vec![(\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n )],\n ),\n // Case 7: More complex chunking with multiple sub-tries\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x2f)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(3),\n ProofV2Target::new(B256::repeat_byte(0x4c)).with_min_len(4),\n ProofV2Target::new(B256::repeat_byte(0x4e)).with_min_len(3),\n ],\n vec![\n (\n \"2\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f2f\",\n ],\n ),\n (\n \"4c\",\n vec![\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n \"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c\",\n ],\n ),\n (\n \"4e\",\n vec![\"4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e4e\"],\n ),\n ],\n ),\n // Case 8: Min-len 1 should result in zero-length sub-trie prefix\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(1),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(1),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"4040404040404040404040404040404040404040404040404040404040404040\",\n ],\n )],\n ),\n // Case 9: Second target's sub-trie prefix is root\n (\n vec![\n ProofV2Target::new(B256::repeat_byte(0x20)).with_min_len(2),\n ProofV2Target::new(B256::repeat_byte(0x40)).with_min_len(1),\n ],\n vec![(\n \"\",\n vec![\n \"2020202020202020202020202020202020202020202020202020202020202020\",\n \"4040404040404040404040404040404040404040404040404040404040404040\",\n ],\n )],\n ),\n ];\n\n for (i, (mut input_targets, expected)) in test_cases.into_iter().enumerate() {\n let test_case = i + 1;\n let sub_tries: Vec<_> = iter_sub_trie_targets(&mut input_targets).collect();\n\n assert_eq!(\n sub_tries.len(),\n expected.len(),\n \"Test case {} failed: expected {} sub-tries, got {}\",\n test_case,\n expected.len(),\n sub_tries.len()\n );\n\n for (j, (sub_trie, (exp_prefix_hex, exp_keys))) in\n sub_tries.iter().zip(expected.iter()).enumerate()\n {\n let exp_prefix = nibbles(exp_prefix_hex);\n\n assert_eq!(\n sub_trie.prefix, exp_prefix,\n \"Test case {} sub-trie {}: prefix mismatch\",\n test_case, j\n );\n assert_eq!(\n sub_trie.targets.len(),\n exp_keys.len(),\n \"Test case {} sub-trie {}: expected {} targets, got {}\",\n test_case,\n j,\n exp_keys.len(),\n sub_trie.targets.len()\n );\n\n for (k, (target, exp_key_hex)) in\n sub_trie.targets.iter().zip(exp_keys.iter()).enumerate()\n {\n let exp_key = nibbles(exp_key_hex);\n assert_eq!(\n target.key_nibbles, exp_key,\n \"Test case {} sub-trie {} target {}: key mismatch\",\n test_case, j, k\n );\n }\n }\n }\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n", "middle": "#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\n", "suffix": "use alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\n", "middle": "use alloy_primitives::{map::B256Map, B256};\n", "suffix": "use reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\n", "middle": "use reth_ethereum_primitives::BlockBody;\n", "suffix": "use reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\n", "middle": "use reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\n", "suffix": "use std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\n", "middle": "use std::ops::RangeInclusive;\n", "suffix": "\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\n", "middle": "mod bodies_client;\n", "suffix": "pub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Mod"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\n", "middle": "pub use bodies_client::TestBodiesClient;\n", "suffix": "use reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\n", "middle": "use reth_primitives_traits::SealedHeader;\n", "suffix": "\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n", "middle": "/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n", "suffix": "\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Const"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n", "middle": " use futures::SinkExt;\n", "suffix": " use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n", "middle": " use std::io::SeekFrom;\n", "suffix": " use tokio::{fs::File, io::AsyncSeekExt};\n use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n", "middle": " use tokio::{fs::File, io::AsyncSeekExt};\n", "suffix": " use tokio_util::codec::FramedWrite;\n\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/net/downloaders/src/test_utils/mod.rs", "prefix": "//! Test helper impls.\n\n#![allow(dead_code)]\n\n#[cfg(any(test, feature = \"file-client\"))]\nuse crate::{bodies::test_utils::create_raw_bodies, file_codec::BlockFileCodec};\nuse alloy_primitives::{map::B256Map, B256};\nuse reth_ethereum_primitives::BlockBody;\nuse reth_testing_utils::generators::{self, random_block_range, BlockRangeParams};\nuse std::ops::RangeInclusive;\n\nmod bodies_client;\npub use bodies_client::TestBodiesClient;\nuse reth_primitives_traits::SealedHeader;\n\n/// Metrics scope used for testing.\npub(crate) const TEST_SCOPE: &str = \"downloaders.test\";\n\n/// Generate a set of bodies and their corresponding block hashes\npub(crate) fn generate_bodies(\n range: RangeInclusive,\n) -> (Vec, B256Map) {\n let mut rng = generators::rng();\n let blocks = random_block_range(\n &mut rng,\n range,\n BlockRangeParams { parent: Some(B256::ZERO), tx_count: 0..2, ..Default::default() },\n );\n\n let headers = blocks.iter().map(|block| block.clone_sealed_header()).collect();\n let bodies = blocks.into_iter().map(|block| (block.hash(), block.into_body())).collect();\n\n (headers, bodies)\n}\n\n/// Generate a set of bodies, write them to a temporary file, and return the file along with the\n/// bodies and corresponding block hashes\n#[cfg(any(test, feature = \"file-client\"))]\npub(crate) async fn generate_bodies_file(\n range: RangeInclusive,\n) -> (tokio::fs::File, Vec, B256Map) {\n use futures::SinkExt;\n use std::io::SeekFrom;\n use tokio::{fs::File, io::AsyncSeekExt};\n", "middle": " use tokio_util::codec::FramedWrite;\n", "suffix": "\n let (headers, bodies) = generate_bodies(range);\n let raw_block_bodies = create_raw_bodies(headers.iter().cloned(), &mut bodies.clone());\n\n let file: File = tempfile::tempfile().unwrap().into();\n let mut writer = FramedWrite::new(file, BlockFileCodec::default());\n\n // rlp encode one after the other\n for block in raw_block_bodies {\n writer.feed(block).await.unwrap();\n }\n writer.flush().await.unwrap();\n\n // get the file back\n let mut file: File = writer.into_inner();\n file.seek(SeekFrom::Start(0)).await.unwrap();\n (file, headers, bodies)\n}\n", "nodeType": "Use"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "", "middle": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\n", "suffix": "use reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Use"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\n", "middle": "use reth_primitives_traits::ValueWithSubKey;\n", "suffix": "\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Use"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\n", "middle": "impl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n", "suffix": "\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Impl"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n", "middle": " fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n", "suffix": "}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey ", "middle": "{\n self.nibbles.clone()\n }", "suffix": "\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n", "middle": " fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n", "suffix": "\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n ", "middle": "{\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }", "suffix": "\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n", "middle": " fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n", "suffix": "}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) ", "middle": "{\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }", "suffix": "\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\n", "middle": "impl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n", "suffix": "\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Impl"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n", "middle": " fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n", "suffix": "}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey ", "middle": "{\n self.nibbles.clone()\n }", "suffix": "\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n", "middle": " fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n", "suffix": "\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n ", "middle": "{\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }", "suffix": "\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n", "middle": " fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }\n", "suffix": "}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "Function"} {"filePath": "crates/trie/common/src/storage.rs", "prefix": "use super::{BranchNodeCompact, PackedStoredNibblesSubKey, StoredNibblesSubKey};\nuse reth_primitives_traits::ValueWithSubKey;\n\n/// Account storage trie node.\n///\n/// `nibbles` is the subkey when used as a value in the `StorageTrie` table.\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct StorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: StoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for StorageTrieEntry {\n type SubKey = StoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n// NOTE: Removing reth_codec and manually encode subkey\n// and compress second part of the value. If we have compression\n// over whole value (Even SubKey) that would mess up fetching of values with seek_by_key_subkey\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for StorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {\n let (nibbles, buf) = StoredNibblesSubKey::from_compact(buf, 65);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 65);\n let this = Self { nibbles, node };\n (this, buf)\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(StorageTrieEntry);\n\n/// Account storage trie node with packed nibble encoding (storage v2).\n///\n/// Same as [`StorageTrieEntry`] but uses [`PackedStoredNibblesSubKey`] (33 bytes)\n/// instead of [`StoredNibblesSubKey`] (65 bytes).\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(any(test, feature = \"serde\"), derive(serde::Serialize, serde::Deserialize))]\npub struct PackedStorageTrieEntry {\n /// The nibbles of the intermediate node\n pub nibbles: PackedStoredNibblesSubKey,\n /// Encoded node.\n pub node: BranchNodeCompact,\n}\n\nimpl ValueWithSubKey for PackedStorageTrieEntry {\n type SubKey = PackedStoredNibblesSubKey;\n\n fn get_subkey(&self) -> Self::SubKey {\n self.nibbles.clone()\n }\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nimpl reth_codecs::Compact for PackedStorageTrieEntry {\n fn to_compact(&self, buf: &mut B) -> usize\n where\n B: bytes::BufMut + AsMut<[u8]>,\n {\n let nibbles_len = self.nibbles.to_compact(buf);\n let node_len = self.node.to_compact(buf);\n nibbles_len + node_len\n }\n\n fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) ", "middle": "{\n let (nibbles, buf) = PackedStoredNibblesSubKey::from_compact(buf, 33);\n let (node, buf) = BranchNodeCompact::from_compact(buf, len - 33);\n (Self { nibbles, node }, buf)\n }", "suffix": "\n}\n\n#[cfg(any(test, feature = \"reth-codec\"))]\nreth_codecs::impl_compression_for_compact!(PackedStorageTrieEntry);\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "", "middle": "use crate::{compression::Compression, NippyJarError};\n", "suffix": "use derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n ", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\n", "middle": "use derive_more::Deref;\n", "suffix": "use serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n ", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\n", "middle": "use serde::{Deserialize, Deserializer, Serialize, Serializer};\n", "suffix": "use std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n bu", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n", "middle": "use std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\n", "suffix": "use tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, se", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\n", "middle": "use tracing::*;\n", "suffix": "use zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n d", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\n", "middle": "use zstd::bulk::Compressor;\n", "suffix": "pub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictio", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\n", "middle": "pub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n", "suffix": "\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.di", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\n", "middle": "type RawDictionary = Vec;\n", "suffix": "\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with", "nodeType": "Other"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n", "middle": "/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n", "suffix": "\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let pr", "nodeType": "Enum"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n", "middle": "#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n", "suffix": "\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionar", "nodeType": "Struct"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n", "middle": " pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n", "suffix": "\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDict", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self ", "middle": "{\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }", "suffix": "\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n ", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n", "middle": " pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n", "suffix": "\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self ", "middle": "{\n self.level = level;\n self\n }", "suffix": "\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n", "middle": " pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n", "suffix": "\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors fro", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> ", "middle": "{\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }", "suffix": "\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n ", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n", "middle": " pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n", "suffix": "\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns:", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> ", "middle": "{\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }", "suffix": "\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n", "middle": " pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n", "suffix": "\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) c", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> ", "middle": "{\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }", "suffix": "\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictiona", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n", "middle": " pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n", "suffix": "}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "n level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> ", "middle": "{\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }", "suffix": "\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n", "middle": " fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n", "suffix": "\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "dingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> ", "middle": "{\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }", "suffix": "\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n ", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n", "middle": " fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n", "suffix": "\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> ", "middle": "{\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }", "suffix": "\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "ippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n", "middle": " fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n", "suffix": "\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n ", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result ", "middle": "{\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }", "suffix": "\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n", "middle": " fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n", "suffix": "\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "use crate::{compression::Compression, NippyJarError};\nuse derive_more::Deref;\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\nuse std::{\n fs::File,\n io::{Read, Write},\n sync::Arc,\n};\nuse tracing::*;\nuse zstd::bulk::Compressor;\npub use zstd::{bulk::Decompressor, dict::DecoderDictionary};\n\ntype RawDictionary = Vec;\n\n/// Represents the state of a Zstandard compression operation.\n#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> ", "middle": "{\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }", "suffix": "\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n", "middle": " fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n", "suffix": "\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::wi", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool ", "middle": "{\n matches!(self.state, ZstdState::Ready)\n }", "suffix": "\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dic", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "{\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\n", "middle": "mod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n", "suffix": "\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n ", "nodeType": "Mod"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " Serialize, Deserialize)]\npub enum ZstdState {\n /// The compressor is pending a dictionary.\n #[default]\n PendingDictionary,\n /// The compressor is ready to perform compression.\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n", "middle": " use super::*;\n", "suffix": "\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": ".\n Ready,\n}\n\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Debug, Serialize, Deserialize)]\n/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n", "middle": " pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n", "suffix": "\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "/// Zstd compression structure. Supports a compression dictionary per column.\npub struct Zstd {\n /// State. Should be ready before compressing.\n pub(crate) state: ZstdState,\n /// Compression level. A level of `0` uses zstd's default (currently `3`).\n pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n ", "middle": "{\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }", "suffix": "\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " pub(crate) level: i32,\n /// Uses custom dictionaries to compress data.\n pub use_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n", "middle": " pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n", "suffix": "}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "se_dict: bool,\n /// Max size of a dictionary\n pub(crate) max_dict_size: usize,\n /// List of column dictionaries.\n #[serde(with = \"dictionaries_serde\")]\n pub(crate) dictionaries: Option>>,\n /// Number of columns to compress.\n columns: usize,\n}\n\nimpl Zstd {\n /// Creates new [`Zstd`].\n pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n ", "middle": "{\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }", "suffix": "\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n", "middle": "/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n", "suffix": "\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "dict_size: usize, columns: usize) -> Self {\n Self {\n state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready },\n level: 0,\n use_dict,\n max_dict_size,\n dictionaries: None,\n columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\n", "middle": "impl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n", "suffix": "\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n", "middle": " fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n", "suffix": "}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result ", "middle": "{\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }", "suffix": "\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " columns,\n }\n }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n", "middle": " pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n", "suffix": "\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " }\n\n /// Sets the compression level for the Zstd compression instance.\n pub const fn with_level(mut self, level: i32) -> Self {\n self.level = level;\n self\n }\n\n /// Creates a list of [`Decompressor`] if using dictionaries.\n pub fn decompressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self ", "middle": "{\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }", "suffix": "\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "ize, NippyJarError> {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n", "middle": " pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n", "suffix": "\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "compressors(&self) -> Result>, NippyJarError> {\n if let Some(dictionaries) = &self.dictionaries {\n debug_assert!(dictionaries.len() == self.columns);\n return dictionaries.decompressors()\n }\n\n Ok(vec![])\n }\n\n /// If using dictionaries, creates a list of [`Compressor`].\n pub fn compressors(&self) -> Result>>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self ", "middle": "{\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }", "suffix": "\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n", "middle": " pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n", "suffix": "\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": ">>, NippyJarError> {\n match self.state {\n ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady),\n ZstdState::Ready => {\n if !self.use_dict {\n return Ok(None)\n }\n\n if let Some(dictionaries) = &self.dictionaries {\n debug!(target: \"nippy-jar\", count=?dictionaries.len(), \"Generating ZSTD compressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> ", "middle": "{\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }", "suffix": "\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "mpressor dictionaries.\");\n return Ok(Some(dictionaries.compressors()?))\n }\n Ok(None)\n }\n }\n }\n\n /// Compresses a value using a dictionary. Reserves additional capacity for `buffer` if\n /// necessary.\n pub fn compress_with_dictionary(\n column_value: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n", "middle": " pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n", "suffix": "}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "ata set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> ", "middle": "{\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }", "suffix": "\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "e: &[u8],\n buffer: &mut Vec,\n handle: &mut File,\n compressor: Option<&mut Compressor<'_>>,\n ) -> Result<(), NippyJarError> {\n if let Some(compressor) = compressor {\n // Compressor requires the destination buffer to be big enough to write, otherwise it\n // fails. However, we don't know how big it will be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n", "middle": "/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n", "suffix": "\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Enum"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "fer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\n", "middle": "impl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n", "suffix": "\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "/ ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n", "middle": " pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n", "suffix": "\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "ill be. If data is small\n // enough, the compressed buffer will actually be larger. We keep retrying.\n // If we eventually fail, it probably means it's another kind of error.\n let mut multiplier = 1;\n while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> ", "middle": "{\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }", "suffix": "\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " while let Err(err) = compressor.compress_to_buffer(column_value, buffer) {\n buffer.reserve(column_value.len() * multiplier);\n multiplier += 1;\n if multiplier == 5 {\n return Err(NippyJarError::Disconnect(err))\n }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n", "middle": " pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n", "suffix": "}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "us in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> ", "middle": "{\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }", "suffix": "\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\n", "middle": "impl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n", "suffix": "\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " }\n }\n\n handle.write_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n", "middle": " fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n", "suffix": "}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "te_all(buffer)?;\n buffer.clear();\n } else {\n handle.write_all(column_value)?;\n }\n\n Ok(())\n }\n\n /// Appends a decompressed value using a dictionary to a user provided buffer.\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n ", "middle": "{\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }", "suffix": "\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": ".\n pub fn decompress_with_dictionary(\n column_value: &[u8],\n output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\n", "middle": "impl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n", "suffix": "\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "naries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n", "middle": " fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n", "suffix": "}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " output: &mut Vec,\n decompressor: &mut Decompressor<'_>,\n ) -> Result<(), NippyJarError> {\n let previous_length = output.len();\n\n // SAFETY: We're setting len to the existing capacity.\n unsafe {\n output.set_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n ", "middle": "{\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }", "suffix": "\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "t_len(output.capacity());\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n", "middle": "#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n}\n", "suffix": "", "nodeType": "Impl"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": "\n }\n\n match decompressor.decompress_to_buffer(column_value, &mut output[previous_length..]) {\n Ok(written) => {\n // SAFETY: `decompress_to_buffer` can only write if there's enough capacity.\n // Therefore, it shouldn't write more than our capacity.\n unsafe {\n output.set_len(previous_length + written);\n }\n Ok(())\n }\n Err(_) => {\n // SAFETY: we are resetting it to the previous value.\n unsafe {\n output.set_len(previous_length);\n }\n Err(NippyJarError::OutputTooSmall)\n }\n }\n }\n}\n\nimpl Compression for Zstd {\n fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> {\n let mut decoder = zstd::Decoder::with_dictionary(value, &[])?;\n decoder.read_to_end(dest)?;\n Ok(())\n }\n\n fn decompress(&self, value: &[u8]) -> Result, NippyJarError> {\n let mut decompressed = Vec::with_capacity(value.len() * 2);\n let mut decoder = zstd::Decoder::new(value)?;\n decoder.read_to_end(&mut decompressed)?;\n Ok(decompressed)\n }\n\n fn compress_to(&self, src: &[u8], dest: &mut Vec) -> Result {\n let before = dest.len();\n\n let mut encoder = zstd::Encoder::new(dest, self.level)?;\n encoder.write_all(src)?;\n\n let dest = encoder.finish()?;\n\n Ok(dest.len() - before)\n }\n\n fn compress(&self, src: &[u8]) -> Result, NippyJarError> {\n let mut compressed = Vec::with_capacity(src.len());\n\n self.compress_to(src, &mut compressed)?;\n\n Ok(compressed)\n }\n\n fn is_ready(&self) -> bool {\n matches!(self.state, ZstdState::Ready)\n }\n\n #[cfg(test)]\n /// If using it with dictionaries, prepares a dictionary for each column.\n fn prepare_compression(\n &mut self,\n columns: Vec>>,\n ) -> Result<(), NippyJarError> {\n if !self.use_dict {\n return Ok(())\n }\n\n // There's a per 2GB hard limit on each column data set for training\n // REFERENCE: https://github.com/facebook/zstd/blob/dev/programs/zstd.1.md#dictionary-builder\n // ```\n // -M#, --memory=#: Limit the amount of sample data loaded for training (default: 2 GB).\n // Note that the default (2 GB) is also the maximum. This parameter can be useful in\n // situations where the training set size is not well controlled and could be potentially\n // very large. Since speed of the training process is directly correlated to the size of the\n // training sample set, a smaller sample set leads to faster training.`\n // ```\n\n if columns.len() != self.columns {\n return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len()))\n }\n\n let mut dictionaries = Vec::with_capacity(columns.len());\n for column in columns {\n // ZSTD requires all training data to be continuous in memory, alongside the size of\n // each entry\n let mut sizes = vec![];\n let data: Vec<_> = column\n .into_iter()\n .flat_map(|data| {\n sizes.push(data.len());\n data\n })\n .collect();\n\n dictionaries.push(zstd::dict::from_continuous(&data, &sizes, self.max_dict_size)?);\n }\n\n debug_assert_eq!(dictionaries.len(), self.columns);\n\n self.dictionaries = Some(Arc::new(ZstdDictionaries::new(dictionaries)));\n self.state = ZstdState::Ready;\n\n Ok(())\n }\n}\n\nmod dictionaries_serde {\n use super::*;\n\n pub(crate) fn serialize(\n dictionaries: &Option>>,\n serializer: S,\n ) -> Result\n where\n S: Serializer,\n {\n match dictionaries {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n", "middle": " fn eq(&self, other: &Self) -> bool {\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/storage/nippy-jar/src/compression/zstd.rs", "prefix": " {\n Some(dicts) => serializer.serialize_some(dicts.as_ref()),\n None => serializer.serialize_none(),\n }\n }\n\n pub(crate) fn deserialize<'de, D>(\n deserializer: D,\n ) -> Result>>, D::Error>\n where\n D: Deserializer<'de>,\n {\n let dictionaries: Option> = Option::deserialize(deserializer)?;\n Ok(dictionaries.map(|dicts| Arc::new(ZstdDictionaries::load(dicts))))\n }\n}\n\n/// List of [`ZstdDictionary`]\n#[cfg_attr(test, derive(PartialEq))]\n#[derive(Serialize, Deserialize, Deref)]\npub(crate) struct ZstdDictionaries<'a>(Vec>);\n\nimpl std::fmt::Debug for ZstdDictionaries<'_> {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"ZstdDictionaries\").field(\"num\", &self.len()).finish_non_exhaustive()\n }\n}\n\nimpl ZstdDictionaries<'_> {\n #[cfg(test)]\n /// Creates [`ZstdDictionaries`].\n pub(crate) fn new(raw: Vec) -> Self {\n Self(raw.into_iter().map(ZstdDictionary::Raw).collect())\n }\n\n /// Loads a list [`RawDictionary`] into a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn load(raw: Vec) -> Self {\n Self(\n raw.into_iter()\n .map(|dict| ZstdDictionary::Loaded(DecoderDictionary::copy(&dict)))\n .collect(),\n )\n }\n\n /// Creates a list of decompressors from a list of [`ZstdDictionary::Loaded`].\n pub(crate) fn decompressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.loaded()\n .ok_or(NippyJarError::DictionaryNotLoaded)\n .map(Decompressor::with_prepared_dictionary)\n })\n .collect::, _>>()?)\n }\n\n /// Creates a list of compressors from a list of [`ZstdDictionary::Raw`].\n pub(crate) fn compressors(&self) -> Result>, NippyJarError> {\n Ok(self\n .iter()\n .flat_map(|dict| {\n dict.raw()\n .ok_or(NippyJarError::CompressorNotAllowed)\n .map(|dict| Compressor::with_dictionary(0, dict))\n })\n .collect::, _>>()?)\n }\n}\n\n/// A Zstd dictionary. It's created and serialized with [`ZstdDictionary::Raw`], and deserialized as\n/// [`ZstdDictionary::Loaded`].\npub(crate) enum ZstdDictionary<'a> {\n #[cfg_attr(not(test), expect(dead_code))]\n Raw(RawDictionary),\n Loaded(DecoderDictionary<'a>),\n}\n\nimpl ZstdDictionary<'_> {\n /// Returns a reference to the expected `RawDictionary`\n pub(crate) const fn raw(&self) -> Option<&RawDictionary> {\n match self {\n ZstdDictionary::Raw(dict) => Some(dict),\n ZstdDictionary::Loaded(_) => None,\n }\n }\n\n /// Returns a reference to the expected `DecoderDictionary`\n pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> {\n match self {\n ZstdDictionary::Raw(_) => None,\n ZstdDictionary::Loaded(dict) => Some(dict),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for ZstdDictionary<'_> {\n fn deserialize(deserializer: D) -> Result\n where\n D: Deserializer<'de>,\n {\n let dict = RawDictionary::deserialize(deserializer)?;\n Ok(Self::Loaded(DecoderDictionary::copy(&dict)))\n }\n}\n\nimpl Serialize for ZstdDictionary<'_> {\n fn serialize(&self, serializer: S) -> Result\n where\n S: Serializer,\n {\n match self {\n ZstdDictionary::Raw(r) => r.serialize(serializer),\n ZstdDictionary::Loaded(_) => unreachable!(),\n }\n }\n}\n\n#[cfg(test)]\nimpl PartialEq for ZstdDictionary<'_> {\n fn eq(&self, other: &Self) -> bool ", "middle": "{\n if let (Self::Raw(a), Self::Raw(b)) = (self, &other) {\n return a == b\n }\n unimplemented!(\n \"`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value.\"\n );\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/rpc/rpc-api/src/testing.rs", "prefix": "//! Testing namespace for building a block in a single call.\n//!\n//! This follows the `testing_buildBlockV1` specification. **Highly sensitive:**\n//! testing-only, powerful enough to include arbitrary transactions; must stay\n//! disabled by default and never be exposed on public-facing RPC without an\n//! explicit operator flag.\n\n", "middle": "use alloy_rpc_types_engine::ExecutionPayloadEnvelopeV5;\n", "suffix": "use jsonrpsee::proc_macros::rpc;\n\npub use alloy_rpc_types_engine::{TestingBuildBlockRequestV1, TESTING_BUILD_BLOCK_V1};\n\n/// Testing RPC interface for building a block in a single call.\n///\n/// # Enabling\n///\n/// This namespace is disabled by default for security reasons. To enable it,\n/// add `testing` to the `--http.api` flag:\n///\n/// ```sh\n/// reth node --http --http.api eth,testing\n/// ```\n///\n/// **Warning:** Never expose this on public-facing RPC endpoints without proper\n/// authentication.\n#[cfg_attr(not(feature = \"client\"), rpc(server, namespace = \"testing\"))]\n#[cfg_attr(feature = \"client\", rpc(server, client, namespace = \"testing\"))]\npub trait TestingApi {\n /// Builds a block using the provided parent, payload attributes, and transactions.\n ///\n /// See \n #[method(name = \"buildBlockV1\")]\n async fn build_block_v1(\n &self,\n request: TestingBuildBlockRequestV1,\n ) -> jsonrpsee::core::RpcResult;\n}\n", "nodeType": "Use"} {"filePath": "crates/rpc/rpc-api/src/testing.rs", "prefix": "//! Testing namespace for building a block in a single call.\n//!\n//! This follows the `testing_buildBlockV1` specification. **Highly sensitive:**\n//! testing-only, powerful enough to include arbitrary transactions; must stay\n//! disabled by default and never be exposed on public-facing RPC without an\n//! explicit operator flag.\n\nuse alloy_rpc_types_engine::ExecutionPayloadEnvelopeV5;\n", "middle": "use jsonrpsee::proc_macros::rpc;\n", "suffix": "\npub use alloy_rpc_types_engine::{TestingBuildBlockRequestV1, TESTING_BUILD_BLOCK_V1};\n\n/// Testing RPC interface for building a block in a single call.\n///\n/// # Enabling\n///\n/// This namespace is disabled by default for security reasons. To enable it,\n/// add `testing` to the `--http.api` flag:\n///\n/// ```sh\n/// reth node --http --http.api eth,testing\n/// ```\n///\n/// **Warning:** Never expose this on public-facing RPC endpoints without proper\n/// authentication.\n#[cfg_attr(not(feature = \"client\"), rpc(server, namespace = \"testing\"))]\n#[cfg_attr(feature = \"client\", rpc(server, client, namespace = \"testing\"))]\npub trait TestingApi {\n /// Builds a block using the provided parent, payload attributes, and transactions.\n ///\n /// See \n #[method(name = \"buildBlockV1\")]\n async fn build_block_v1(\n &self,\n request: TestingBuildBlockRequestV1,\n ) -> jsonrpsee::core::RpcResult;\n}\n", "nodeType": "Use"} {"filePath": "crates/rpc/rpc-api/src/testing.rs", "prefix": "//! Testing namespace for building a block in a single call.\n//!\n//! This follows the `testing_buildBlockV1` specification. **Highly sensitive:**\n//! testing-only, powerful enough to include arbitrary transactions; must stay\n//! disabled by default and never be exposed on public-facing RPC without an\n//! explicit operator flag.\n\nuse alloy_rpc_types_engine::ExecutionPayloadEnvelopeV5;\nuse jsonrpsee::proc_macros::rpc;\n\n", "middle": "pub use alloy_rpc_types_engine::{TestingBuildBlockRequestV1, TESTING_BUILD_BLOCK_V1};\n", "suffix": "\n/// Testing RPC interface for building a block in a single call.\n///\n/// # Enabling\n///\n/// This namespace is disabled by default for security reasons. To enable it,\n/// add `testing` to the `--http.api` flag:\n///\n/// ```sh\n/// reth node --http --http.api eth,testing\n/// ```\n///\n/// **Warning:** Never expose this on public-facing RPC endpoints without proper\n/// authentication.\n#[cfg_attr(not(feature = \"client\"), rpc(server, namespace = \"testing\"))]\n#[cfg_attr(feature = \"client\", rpc(server, client, namespace = \"testing\"))]\npub trait TestingApi {\n /// Builds a block using the provided parent, payload attributes, and transactions.\n ///\n /// See \n #[method(name = \"buildBlockV1\")]\n async fn build_block_v1(\n &self,\n request: TestingBuildBlockRequestV1,\n ) -> jsonrpsee::core::RpcResult;\n}\n", "nodeType": "Use"} {"filePath": "crates/static-file/types/src/compression.rs", "prefix": "", "middle": "use strum::AsRefStr;\n", "suffix": "\n/// Static File compression types.\n#[derive(Debug, Copy, Clone, Default, AsRefStr)]\n#[cfg_attr(feature = \"clap\", derive(clap::ValueEnum))]\npub enum Compression {\n /// LZ4 compression algorithm.\n #[strum(serialize = \"lz4\")]\n Lz4,\n /// Zstandard (Zstd) compression algorithm.\n #[strum(serialize = \"zstd\")]\n Zstd,\n /// Zstandard (Zstd) compression algorithm with a dictionary.\n #[strum(serialize = \"zstd-dict\")]\n ZstdWithDictionary,\n /// No compression.\n #[strum(serialize = \"uncompressed\")]\n #[default]\n Uncompressed,\n}\n", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "", "middle": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\n", "suffix": "use alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n ", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\n", "middle": "use alloy_consensus::EMPTY_ROOT_HASH;\n", "suffix": "use alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\n", "middle": "use alloy_primitives::{keccak256, Address, B256};\n", "suffix": "use alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\n", "middle": "use alloy_rlp::{BufMut, Encodable};\n", "suffix": "use alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\n", "middle": "use alloy_trie::proof::AddedRemovedKeys;\n", "suffix": "use reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calcu", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\n", "middle": "use reth_execution_errors::{StateRootError, StorageRootError};\n", "suffix": "use reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n ", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\n", "middle": "use reth_primitives_traits::Account;\n", "suffix": "use tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n ", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\n", "middle": "use tracing::{debug, instrument, trace, Span};\n", "suffix": "\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => u", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n", "middle": "/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n", "suffix": "\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n ", "nodeType": "Const"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n", "middle": "#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n", "suffix": "\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n ", "nodeType": "Use"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n", "middle": "/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n", "suffix": "\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entri", "nodeType": "Struct"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\n", "middle": "impl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n", "suffix": "\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix", "nodeType": "Impl"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n", "middle": " pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n", "suffix": "\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root cal", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self ", "middle": "{\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }", "suffix": "\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n", "middle": " pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n", "suffix": "\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self ", "middle": "{\n self.prefix_sets = prefix_sets;\n self\n }", "suffix": "\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_u", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n", "middle": " pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n", "suffix": "\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n ac", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self ", "middle": "{\n self.threshold = threshold;\n self\n }", "suffix": "\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n", "middle": " pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n", "suffix": "\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n se", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self ", "middle": "{\n self.threshold = u64::MAX;\n self\n }", "suffix": "\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n", "middle": " pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n", "suffix": "\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self ", "middle": "{\n self.previous_state = state;\n self\n }", "suffix": "\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feat", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n", "middle": " pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n", "suffix": "\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n acco", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot ", "middle": "{\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }", "suffix": "\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n", "middle": " pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n", "suffix": "}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = Storage", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot ", "middle": "{\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }", "suffix": "\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.tr", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n", "middle": " pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n", "suffix": "\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "ror};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> ", "middle": "{\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }", "suffix": "\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n", "middle": " pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n", "suffix": "\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result ", "middle": "{\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }", "suffix": "\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n", "middle": " pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n", "suffix": "\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buff", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "use crate::{\n hashed_cursor::{HashedCursor, HashedCursorFactory, HashedStorageCursor},\n node_iter::{TrieElement, TrieNodeIter},\n prefix_set::{PrefixSet, TriePrefixSets},\n progress::{\n IntermediateRootState, IntermediateStateRootState, IntermediateStorageRootState,\n StateRootProgress, StorageRootProgress,\n },\n stats::TrieTracker,\n trie_cursor::{TrieCursor, TrieCursorFactory},\n updates::{StorageTrieUpdates, TrieUpdates},\n walker::TrieWalker,\n HashBuilder, Nibbles, TRIE_ACCOUNT_RLP_MAX_SIZE,\n};\nuse alloy_consensus::EMPTY_ROOT_HASH;\nuse alloy_primitives::{keccak256, Address, B256};\nuse alloy_rlp::{BufMut, Encodable};\nuse alloy_trie::proof::AddedRemovedKeys;\nuse reth_execution_errors::{StateRootError, StorageRootError};\nuse reth_primitives_traits::Account;\nuse tracing::{debug, instrument, trace, Span};\n\n/// The default updates after which root algorithms should return intermediate progress rather than\n/// finishing the computation.\nconst DEFAULT_INTERMEDIATE_THRESHOLD: u64 = 100_000;\n\n#[cfg(feature = \"metrics\")]\nuse crate::metrics::{StateRootMetrics, TrieRootMetrics};\n\n/// `StateRoot` is used to compute the root node of a state trie.\n#[derive(Debug)]\npub struct StateRoot {\n /// The factory for trie cursors.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// A set of prefix sets that have changed.\n pub prefix_sets: TriePrefixSets,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n #[cfg(feature = \"metrics\")]\n /// State root metrics.\n metrics: StateRootMetrics,\n}\n\nimpl StateRoot {\n /// Creates [`StateRoot`] with `trie_cursor_factory` and `hashed_cursor_factory`. All other\n /// parameters are set to reasonable defaults.\n ///\n /// The cursors created by given factories are then used to walk through the accounts and\n /// calculate the state root value with.\n pub fn new(trie_cursor_factory: T, hashed_cursor_factory: H) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: TriePrefixSets::default(),\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics: StateRootMetrics::default(),\n }\n }\n\n /// Set the prefix sets.\n pub fn with_prefix_sets(mut self, prefix_sets: TriePrefixSets) -> Self {\n self.prefix_sets = prefix_sets;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StateRoot {\n StateRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StateRoot {\n StateRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n prefix_sets: self.prefix_sets,\n threshold: self.threshold,\n previous_state: self.previous_state,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StateRoot\nwhere\n T: TrieCursorFactory + Clone,\n H: HashedCursorFactory + Clone,\n{\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// Ignores the threshold.\n ///\n /// # Returns\n ///\n /// The state root and the trie updates.\n pub fn root_with_updates(self) -> Result<(B256, TrieUpdates), StateRootError> {\n match self.with_no_threshold().calculate(true)? {\n StateRootProgress::Complete(root, _, updates) => Ok((root, updates)),\n StateRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder.\n ///\n /// # Returns\n ///\n /// The state root hash.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StateRootProgress::Complete(root, _, _) => Ok(root),\n StateRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the intermediate nodes of existing state trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result ", "middle": "{\n self.calculate(true)\n }", "suffix": "\n\n fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n accoun", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "e(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::state_root\", \"calculating state root\");\n let mut tracker = TrieTracker::default();\n\n let trie_cursor = self.trie_cursor_factory.account_trie_cursor()?;\n let hashed_account_cursor = self.hashed_cursor_factory.hashed_account_cursor()?;\n\n // create state root context once for reuse\n let mut storage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n", "middle": "/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n", "suffix": "\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot<", "nodeType": "Struct"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "orage_ctx = StateRootContext::new();\n\n // first handle any in-progress storage root calculation\n let (mut hash_builder, mut account_node_iter) = if let Some(state) = self.previous_state {\n let IntermediateStateRootState { account_root_state, storage_root_state } = state;\n\n // resume account trie iteration\n let mut hash_builder = account_root_state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::state_trie_from_stack(\n trie_cursor,\n account_root_state.walker_stack,\n self.prefix_sets.account_prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let account_node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor)\n .with_last_hashed_key(account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n", "middle": " fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n", "suffix": "\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": ") => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self ", "middle": "{\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }", "suffix": "\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n sel", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "account_root_state.last_hashed_key);\n\n // if we have an in-progress storage root, complete it first\n if let Some(storage_state) = storage_root_state {\n let hashed_address = account_root_state.last_hashed_key;\n let account = storage_state.account;\n\n debug!(\n target: \"trie::state_root\",\n account_nonce = account.nonce,\n account_balance = ?account.balance,\n last_hashed_key = ?account_root_state.last_hashed_key,\n \"Resuming storage root calculation\"\n );\n\n // resume the storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n", "middle": " fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n", "suffix": "\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRo", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n ", "middle": "{\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }", "suffix": "\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metri", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n", "middle": " fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n", "suffix": "\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// T", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "rage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_intermediate_state(Some(storage_state.state))\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // still in progress, need to pause again\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n account_root_state.last_hashed_key,\n Some(storage_state),\n ))\n }\n }\n\n (hash_builder, account_node_iter)\n } else {\n // no intermediate state, create new hash builder and node iter for state root\n // calculation\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n ", "middle": "{\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }", "suffix": "\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": ".with_updates(retain_updates);\n let walker = TrieWalker::state_trie(trie_cursor, self.prefix_sets.account_prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::state_trie(walker, hashed_account_cursor);\n (hash_builder, node_iter)\n };\n\n while let Some(node) = account_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_address, account) => {\n tracker.inc_leaf();\n storage_ctx.hashed_entries_walked += 1;\n\n // calculate storage root, calculating the remaining threshold so we have\n // bounded memory usage even while in the middle of storage root calculation\n let remaining_threshold = self.threshold.saturating_sub(\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder),\n );\n\n let storage_root_calculator = StorageRoot::new_hashed(\n self.trie_cursor_factory.clone(),\n self.hashed_cursor_factory.clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n", "middle": " fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n", "suffix": "}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "uffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> ", "middle": "{\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }", "suffix": "\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "clone(),\n hashed_address,\n self.prefix_sets\n .storage_prefix_sets\n .get(&hashed_address)\n .cloned()\n .unwrap_or_default(),\n #[cfg(feature = \"metrics\")]\n self.metrics.storage_trie.clone(),\n )\n .with_threshold(remaining_threshold);\n\n let storage_result = storage_root_calculator.calculate(retain_updates)?;\n if let Some(storage_state) = storage_ctx.process_storage_root_result(\n storage_result,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n", "middle": "/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n", "suffix": "\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n ", "nodeType": "Struct"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\n", "middle": "impl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n", "suffix": "\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentia", "nodeType": "Impl"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "lt,\n hashed_address,\n account,\n &mut hash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n", "middle": " pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n", "suffix": "\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "ash_builder,\n retain_updates,\n )? {\n // storage root hit threshold, need to pause\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n Some(storage_state),\n ))\n }\n\n // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self ", "middle": "{\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }", "suffix": "\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " // decide if we need to return intermediate progress\n let total_updates_len =\n storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n", "middle": " pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n", "suffix": "\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " storage_ctx.total_updates_len(&account_node_iter, &hash_builder);\n if retain_updates && total_updates_len >= self.threshold {\n return Ok(storage_ctx.create_progress_state(\n account_node_iter,\n hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self ", "middle": "{\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }", "suffix": "\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storag", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n", "middle": " pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n", "suffix": "\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", fo", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " hash_builder,\n hashed_address,\n None,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n\n let removed_keys = account_node_iter.walker.take_removed_keys();\n let StateRootContext { mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self ", "middle": "{\n self.prefix_set = prefix_set;\n self\n }", "suffix": "\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "rageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n", "middle": " pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n", "suffix": "\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n S", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self ", "middle": "{\n self.threshold = threshold;\n self\n }", "suffix": "\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "Error> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n", "middle": " pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n", "suffix": "\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cu", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " mut trie_updates, hashed_entries_walked, .. } = storage_ctx;\n trie_updates.finalize(hash_builder, removed_keys, self.prefix_sets.destroyed_accounts);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.state_trie.record(stats);\n\n trace!(\n target: \"trie::state_root\",\n %root,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self ", "middle": "{\n self.threshold = u64::MAX;\n self\n }", "suffix": "\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Cu", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n", "middle": " pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n", "suffix": "\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n ", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "ts_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self ", "middle": "{\n self.previous_state = state;\n self\n }", "suffix": "\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_up", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "lculated state root\"\n );\n\n Ok(StateRootProgress::Complete(root, hashed_entries_walked, trie_updates))\n }\n}\n\n/// Contains state mutated during state root calculation and storage root result handling.\n#[derive(Debug)]\npub(crate) struct StateRootContext {\n /// Reusable buffer for encoding account data.\n account_rlp: Vec,\n /// Accumulates updates from account and storage root calculation.\n trie_updates: TrieUpdates,\n /// Tracks total hashed entries walked.\n hashed_entries_walked: usize,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n", "middle": " pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n", "suffix": "\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "nt = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot ", "middle": "{\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }", "suffix": "\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_stora", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "size,\n /// Counts storage trie nodes updated.\n updated_storage_nodes: usize,\n}\n\nimpl StateRootContext {\n /// Creates a new state root context.\n fn new() -> Self {\n Self {\n account_rlp: Vec::with_capacity(TRIE_ACCOUNT_RLP_MAX_SIZE),\n trie_updates: TrieUpdates::default(),\n hashed_entries_walked: 0,\n updated_storage_nodes: 0,\n }\n }\n\n /// Creates a [`StateRootProgress`] when the threshold is hit, from the state of the current\n /// [`TrieNodeIter`], [`HashBuilder`], last hashed key and any storage root intermediate state.\n fn create_progress_state(\n mut self,\n account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n", "middle": " pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n", "suffix": "}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "hed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot ", "middle": "{\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }", "suffix": "\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_ite", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " account_node_iter: TrieNodeIter,\n hash_builder: HashBuilder,\n last_hashed_key: B256,\n storage_state: Option,\n ) -> StateRootProgress\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split();\n self.trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n self.trie_updates.account_nodes.extend(hash_builder_updates);\n\n let account_state = IntermediateRootState { hash_builder, walker_stack, last_hashed_key };\n\n let state = IntermediateStateRootState {\n account_root_state: account_state,\n storage_root_state: storage_state,\n };\n\n StateRootProgress::Progress(Box::new(state), self.hashed_entries_walked, self.trie_updates)\n }\n\n /// Calculates the total number of updated nodes.\n fn total_updates_len(\n &self,\n account_node_iter: &TrieNodeIter,\n hash_builder: &HashBuilder,\n ) -> u64\n where\n C: TrieCursor,\n H: HashedCursor,\n K: AsRef,\n {\n (self.updated_storage_nodes +\n account_node_iter.walker.removed_keys_len() +\n hash_builder.updates_len()) as u64\n }\n\n /// Processes the result of a storage root calculation.\n ///\n /// Handles both completed and in-progress storage root calculations:\n /// - For completed roots: encodes the account with the storage root, updates the hash builder\n /// with the new account, and updates metrics.\n /// - For in-progress roots: returns the intermediate state for later resumption\n ///\n /// Returns an [`IntermediateStorageRootState`] if the calculation needs to be resumed later, or\n /// `None` if the storage root was successfully computed and added to the trie.\n fn process_storage_root_result(\n &mut self,\n storage_result: StorageRootProgress,\n hashed_address: B256,\n account: Account,\n hash_builder: &mut HashBuilder,\n retain_updates: bool,\n ) -> Result, StateRootError> {\n match storage_result {\n StorageRootProgress::Complete(storage_root, storage_slots_walked, updates) => {\n // Storage root completed\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.updated_storage_nodes += updates.len();\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n // Encode the account with the computed storage root\n self.account_rlp.clear();\n let trie_account = account.into_trie_account(storage_root);\n trie_account.encode(&mut self.account_rlp as &mut dyn BufMut);\n hash_builder.add_leaf(Nibbles::unpack(hashed_address), &self.account_rlp);\n Ok(None)\n }\n StorageRootProgress::Progress(state, storage_slots_walked, updates) => {\n // Storage root hit threshold or resumed calculation hit threshold\n debug!(\n target: \"trie::state_root\",\n ?hashed_address,\n storage_slots_walked,\n last_storage_key = ?state.last_hashed_key,\n ?account,\n \"Pausing storage root calculation\"\n );\n\n self.hashed_entries_walked += storage_slots_walked;\n if retain_updates {\n self.trie_updates.insert_storage_updates(hashed_address, updates);\n }\n\n Ok(Some(IntermediateStorageRootState { state: *state, account }))\n }\n }\n }\n}\n\n/// `StorageRoot` is used to compute the root node of an account storage trie.\n#[derive(Debug)]\npub struct StorageRoot {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n", "middle": " pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n", "suffix": "\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "Root {\n /// A reference to the database transaction.\n pub trie_cursor_factory: T,\n /// The factory for hashed cursors.\n pub hashed_cursor_factory: H,\n /// The hashed address of an account.\n pub hashed_address: B256,\n /// The set of storage slot prefixes that have changed.\n pub prefix_set: PrefixSet,\n /// Previous intermediate state.\n previous_state: Option,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result ", "middle": "{\n self.calculate(true)\n }", "suffix": "\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&val", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "eRootState>,\n /// The number of updates after which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n", "middle": " pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n", "suffix": "\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = st", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " which the intermediate progress should be returned.\n threshold: u64,\n /// Storage root metrics.\n #[cfg(feature = \"metrics\")]\n metrics: TrieRootMetrics,\n}\n\nimpl StorageRoot {\n /// Creates a new storage root calculator given a raw address.\n pub fn new(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n address: Address,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> ", "middle": "{\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }", "suffix": "\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "trics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n", "middle": " pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n", "suffix": "\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_s", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "etrics,\n ) -> Self {\n Self::new_hashed(\n trie_cursor_factory,\n hashed_cursor_factory,\n keccak256(address),\n prefix_set,\n #[cfg(feature = \"metrics\")]\n metrics,\n )\n }\n\n /// Creates a new storage root calculator given a hashed address.\n pub const fn new_hashed(\n trie_cursor_factory: T,\n hashed_cursor_factory: H,\n hashed_address: B256,\n prefix_set: PrefixSet,\n #[cfg(feature = \"metrics\")] metrics: TrieRootMetrics,\n ) -> Self {\n Self {\n trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address,\n prefix_set,\n previous_state: None,\n threshold: DEFAULT_INTERMEDIATE_THRESHOLD,\n #[cfg(feature = \"metrics\")]\n metrics,\n }\n }\n\n /// Set the changed prefixes.\n pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {\n self.prefix_set = prefix_set;\n self\n }\n\n /// Set the threshold.\n pub const fn with_threshold(mut self, threshold: u64) -> Self {\n self.threshold = threshold;\n self\n }\n\n /// Set the threshold to maximum value so that intermediate progress is not returned.\n pub const fn with_no_threshold(mut self) -> Self {\n self.threshold = u64::MAX;\n self\n }\n\n /// Set the previously recorded intermediate state.\n pub fn with_intermediate_state(mut self, state: Option) -> Self {\n self.previous_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result ", "middle": "{\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }", "suffix": "\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n ", "nodeType": "FunctionBody"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "t();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n", "middle": "/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n", "suffix": "\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n}\n", "nodeType": "Enum"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "evious_state = state;\n self\n }\n\n /// Set the hashed cursor factory.\n pub fn with_hashed_cursor_factory(self, hashed_cursor_factory: HF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory: self.trie_cursor_factory,\n hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n\n /// Set the trie cursor factory.\n pub fn with_trie_cursor_factory(self, trie_cursor_factory: TF) -> StorageRoot {\n StorageRoot {\n trie_cursor_factory,\n hashed_cursor_factory: self.hashed_cursor_factory,\n hashed_address: self.hashed_address,\n prefix_set: self.prefix_set,\n previous_state: self.previous_state,\n threshold: self.threshold,\n #[cfg(feature = \"metrics\")]\n metrics: self.metrics,\n }\n }\n}\n\nimpl StorageRoot\nwhere\n T: TrieCursorFactory,\n H: HashedCursorFactory,\n{\n /// Walks the intermediate nodes of existing storage trie (if any) and hashed entries. Feeds the\n /// nodes into the hash builder. Collects the updates in the process.\n ///\n /// # Returns\n ///\n /// The intermediate progress of state root computation.\n pub fn root_with_progress(self) -> Result {\n self.calculate(true)\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root and storage trie updates for a given address.\n pub fn root_with_updates(self) -> Result<(B256, usize, StorageTrieUpdates), StorageRootError> {\n match self.with_no_threshold().calculate(true)? {\n StorageRootProgress::Complete(root, walked, updates) => Ok((root, walked, updates)),\n StorageRootProgress::Progress(..) => unreachable!(), // unreachable threshold\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root.\n pub fn root(self) -> Result {\n match self.calculate(false)? {\n StorageRootProgress::Complete(root, _, _) => Ok(root),\n StorageRootProgress::Progress(..) => unreachable!(), // update retention is disabled\n }\n }\n\n /// Walks the hashed storage table entries for a given address and calculates the storage root.\n ///\n /// # Returns\n ///\n /// The storage root, number of walked entries and trie updates\n /// for a given address if requested.\n #[instrument(skip_all, level = \"trace\", target = \"trie::storage_root\", name = \"storage_trie\", fields(addr = %self.hashed_address, storage_root))]\n pub fn calculate(self, retain_updates: bool) -> Result {\n trace!(target: \"trie::storage_root\", \"calculating storage root\");\n\n let mut hashed_storage_cursor =\n self.hashed_cursor_factory.hashed_storage_cursor(self.hashed_address)?;\n\n // short circuit on empty storage\n if hashed_storage_cursor.is_storage_empty()? {\n Span::current().record(\"storage_root\", format!(\"{EMPTY_ROOT_HASH:?}\"));\n return Ok(StorageRootProgress::Complete(\n EMPTY_ROOT_HASH,\n 0,\n StorageTrieUpdates::deleted(),\n ))\n }\n\n let mut tracker = TrieTracker::default();\n let mut trie_updates = StorageTrieUpdates::default();\n\n let trie_cursor = self.trie_cursor_factory.storage_trie_cursor(self.hashed_address)?;\n\n let (mut hash_builder, mut storage_node_iter) = match self.previous_state {\n Some(state) => {\n let hash_builder = state.hash_builder.with_updates(retain_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\n", "middle": "impl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n}\n", "suffix": "", "nodeType": "Impl"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": "n_updates);\n let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n", "middle": " pub(crate) const fn as_str(&self) -> &'static str {\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/trie/trie/src/trie.rs", "prefix": " let walker = TrieWalker::<_>::storage_trie_from_stack(\n trie_cursor,\n state.walker_stack,\n self.prefix_set,\n )\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor)\n .with_last_hashed_key(state.last_hashed_key);\n (hash_builder, node_iter)\n }\n None => {\n let hash_builder = HashBuilder::default().with_updates(retain_updates);\n let walker = TrieWalker::storage_trie(trie_cursor, self.prefix_set)\n .with_deletions_retained(retain_updates);\n let node_iter = TrieNodeIter::storage_trie(walker, hashed_storage_cursor);\n (hash_builder, node_iter)\n }\n };\n\n let mut hashed_entries_walked = 0;\n while let Some(node) = storage_node_iter.try_next()? {\n match node {\n TrieElement::Branch(node) => {\n tracker.inc_branch();\n hash_builder.add_branch(node.key, node.value, node.children_are_in_trie);\n }\n TrieElement::Leaf(hashed_slot, value) => {\n tracker.inc_leaf();\n hashed_entries_walked += 1;\n hash_builder.add_leaf(\n Nibbles::unpack(hashed_slot),\n alloy_rlp::encode_fixed_size(&value).as_ref(),\n );\n\n // Check if we need to return intermediate progress\n let total_updates_len =\n storage_node_iter.walker.removed_keys_len() + hash_builder.updates_len();\n if retain_updates && total_updates_len as u64 >= self.threshold {\n let (walker_stack, walker_deleted_keys) = storage_node_iter.walker.split();\n trie_updates.removed_nodes.extend(walker_deleted_keys);\n let (hash_builder, hash_builder_updates) = hash_builder.split();\n trie_updates.storage_nodes.extend(hash_builder_updates);\n\n let state = IntermediateRootState {\n hash_builder,\n walker_stack,\n last_hashed_key: hashed_slot,\n };\n\n return Ok(StorageRootProgress::Progress(\n Box::new(state),\n hashed_entries_walked,\n trie_updates,\n ))\n }\n }\n }\n }\n\n let root = hash_builder.root();\n Span::current().record(\"storage_root\", format!(\"{root:?}\"));\n\n let removed_keys = storage_node_iter.walker.take_removed_keys();\n trie_updates.finalize(hash_builder, removed_keys);\n\n let stats = tracker.finish();\n\n #[cfg(feature = \"metrics\")]\n self.metrics.record(stats);\n\n trace!(\n target: \"trie::storage_root\",\n %root,\n hashed_address = %self.hashed_address,\n duration = ?stats.duration(),\n branches_added = stats.branches_added(),\n leaves_added = stats.leaves_added(),\n \"calculated storage root\"\n );\n\n let storage_slots_walked = stats.leaves_added() as usize;\n Ok(StorageRootProgress::Complete(root, storage_slots_walked, trie_updates))\n }\n}\n\n/// Trie type for differentiating between various trie calculations.\n#[derive(Clone, Copy, Debug)]\npub enum TrieType {\n /// State trie type.\n State,\n /// Storage trie type.\n Storage,\n /// Custom trie type. Can be used in ExEx.\n Custom(&'static str),\n}\n\nimpl TrieType {\n #[cfg(feature = \"metrics\")]\n pub(crate) const fn as_str(&self) -> &'static str ", "middle": "{\n match self {\n Self::State => \"state\",\n Self::Storage => \"storage\",\n Self::Custom(s) => s,\n }\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/rpc/rpc/src/eth/helpers/receipt.rs", "prefix": "//! Builds an RPC receipt response w.r.t. data layout of network.\n\n", "middle": "use crate::EthApi;\n", "suffix": "use reth_rpc_convert::RpcConvert;\nuse reth_rpc_eth_api::{helpers::LoadReceipt, FromEvmError, RpcNodeCore};\nuse reth_rpc_eth_types::EthApiError;\n\nimpl LoadReceipt for EthApi\nwhere\n N: RpcNodeCore,\n EthApiError: FromEvmError,\n Rpc: RpcConvert,\n{\n}\n", "nodeType": "Use"} {"filePath": "crates/rpc/rpc/src/eth/helpers/receipt.rs", "prefix": "//! Builds an RPC receipt response w.r.t. data layout of network.\n\nuse crate::EthApi;\n", "middle": "use reth_rpc_convert::RpcConvert;\n", "suffix": "use reth_rpc_eth_api::{helpers::LoadReceipt, FromEvmError, RpcNodeCore};\nuse reth_rpc_eth_types::EthApiError;\n\nimpl LoadReceipt for EthApi\nwhere\n N: RpcNodeCore,\n EthApiError: FromEvmError,\n Rpc: RpcConvert,\n{\n}\n", "nodeType": "Use"} {"filePath": "crates/rpc/rpc/src/eth/helpers/receipt.rs", "prefix": "//! Builds an RPC receipt response w.r.t. data layout of network.\n\nuse crate::EthApi;\nuse reth_rpc_convert::RpcConvert;\nuse reth_rpc_eth_api::{helpers::LoadReceipt, FromEvmError, RpcNodeCore};\n", "middle": "use reth_rpc_eth_types::EthApiError;\n", "suffix": "\nimpl LoadReceipt for EthApi\nwhere\n N: RpcNodeCore,\n EthApiError: FromEvmError,\n Rpc: RpcConvert,\n{\n}\n", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "", "middle": "use crate::utils::eth_payload_attributes;\n", "suffix": "use alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).un", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\n", "middle": "use alloy_consensus::{EthereumTxEnvelope, TxEip4844};\n", "suffix": "use alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n C", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\n", "middle": "use alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\n", "suffix": "use alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n ", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\n", "middle": "use alloy_genesis::Genesis;\n", "suffix": "use alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_ac", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\n", "middle": "use alloy_primitives::B256;\n", "suffix": "use reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n break;\n }\n }\n\n Ok(())\n}\n\n// Test that the pool's maintenance task", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\n", "middle": "use reth_chainspec::{ChainSpecBuilder, MAINNET};\n", "suffix": "use reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\n", "middle": "use reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\n", "suffix": "use reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_ch", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\n", "middle": "use reth_node_builder::{NodeBuilder, NodeHandle};\n", "suffix": "use reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::de", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\n", "middle": "use reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\n", "suffix": "use reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandl", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\n", "middle": "use reth_node_ethereum::EthereumNode;\n", "suffix": "use reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n break;\n }\n }\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Commit`\n// events\n#[tokio::test]\nasync fn maintain_txpool_commit() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\n", "middle": "use reth_primitives_traits::Recovered;\n", "suffix": "use reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_nod", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\n", "middle": "use reth_provider::CanonStateSubscriptions;\n", "suffix": "use reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(Ethereum", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\n", "middle": "use reth_tasks::Runtime;\n", "suffix": "use reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\nuse std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n break;\n }\n }\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Commit`\n// events\n#[tokio::test]\nasync fn maintain_txpool_commit() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simul", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\n", "middle": "use reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\n", "suffix": "use std::{sync::Arc, time::Duration};\n\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n break;\n }\n }\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Commit`\n// events\n#[tokio::test]\nasync fn maintain_txpool_commit() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_", "nodeType": "Use"} {"filePath": "crates/ethereum/node/tests/e2e/pool.rs", "prefix": "use crate::utils::eth_payload_attributes;\nuse alloy_consensus::{EthereumTxEnvelope, TxEip4844};\nuse alloy_eips::{eip1559::ETHEREUM_BLOCK_GAS_LIMIT_30M, Encodable2718};\nuse alloy_genesis::Genesis;\nuse alloy_primitives::B256;\nuse reth_chainspec::{ChainSpecBuilder, MAINNET};\nuse reth_e2e_test_utils::{\n node::NodeTestContext, transaction::TransactionTestContext, wallet::Wallet,\n};\nuse reth_node_builder::{NodeBuilder, NodeHandle};\nuse reth_node_core::{args::RpcServerArgs, node_config::NodeConfig};\nuse reth_node_ethereum::EthereumNode;\nuse reth_primitives_traits::Recovered;\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tasks::Runtime;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore, test_utils::OkValidator, BlockInfo, CoinbaseTipOrdering,\n EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, TransactionPool,\n TransactionPoolExt,\n};\n", "middle": "use std::{sync::Arc, time::Duration};\n", "suffix": "\n// Test that stale transactions could be correctly evicted.\n#[tokio::test]\nasync fn maintain_txpool_stale_eviction() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallet = Wallet::default();\n\n let config = reth_transaction_pool::maintain::MaintainPoolConfig {\n max_tx_lifetime: Duration::from_secs(1),\n ..Default::default()\n };\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n config,\n ),\n );\n\n // create a tx with insufficient gas fee and it will be parked\n let envelop =\n TransactionTestContext::transfer_tx_with_gas_fee(1, Some(8_u128), wallet.inner).await;\n let tx = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop.clone()),\n Default::default(),\n );\n let pooled_tx = EthPooledTransaction::new(tx.clone(), 200);\n\n txpool.add_transaction(TransactionOrigin::External, pooled_tx).await.unwrap();\n assert_eq!(txpool.len(), 1);\n\n tokio::time::sleep(std::time::Duration::from_secs(2)).await;\n\n // stale tx should be evicted\n assert_eq!(txpool.len(), 0);\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Reorg` events\n#[tokio::test]\nasync fn maintain_txpool_reorg() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n .chain(MAINNET.chain)\n .genesis(genesis)\n .cancun_activated()\n .build(),\n );\n let genesis_hash = chain_spec.genesis_hash();\n let node_config = NodeConfig::test()\n .with_chain(chain_spec)\n .with_unused_ports()\n .with_rpc(RpcServerArgs::default().with_unused_ports().with_http());\n let NodeHandle { node, node_exit_future: _ } = NodeBuilder::new(node_config.clone())\n .testing_node(runtime.clone())\n .node(EthereumNode::default())\n .launch()\n .await?;\n\n let mut node = NodeTestContext::new(node, eth_payload_attributes).await?;\n\n let wallets = Wallet::new(2).wallet_gen();\n let w1 = wallets.first().unwrap();\n let w2 = wallets.last().unwrap();\n\n runtime.spawn_critical_task(\n \"txpool maintenance task\",\n reth_transaction_pool::maintain::maintain_transaction_pool_future(\n node.inner.provider.clone(),\n txpool.clone(),\n node.inner.provider.clone().canonical_state_stream(),\n runtime.clone(),\n reth_transaction_pool::maintain::MaintainPoolConfig::default(),\n ),\n );\n\n // build tx1 from wallet1\n let envelop1 = TransactionTestContext::transfer_tx(1, w1.clone()).await;\n let tx1 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop1.clone()),\n w1.address(),\n );\n let pooled_tx1 = EthPooledTransaction::new(tx1.clone(), 200);\n let tx_hash1 = *pooled_tx1.hash();\n\n // build tx2 from wallet2\n let envelop2 = TransactionTestContext::transfer_tx(1, w2.clone()).await;\n let tx2 = Recovered::new_unchecked(\n EthereumTxEnvelope::::from(envelop2.clone()),\n w2.address(),\n );\n let pooled_tx2 = EthPooledTransaction::new(tx2.clone(), 200);\n let tx_hash2 = *pooled_tx2.hash();\n\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n\n txpool.set_block_info(block_info);\n\n // add two txs to the pool\n txpool.add_transaction(TransactionOrigin::External, pooled_tx1).await.unwrap();\n txpool.add_transaction(TransactionOrigin::External, pooled_tx2).await.unwrap();\n\n // inject tx1, make the node advance and eventually generate `CanonStateNotification::Commit`\n // event to propagate to the pool\n let _ = node.rpc.inject_tx(envelop1.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx1\n let payload1 = node.new_payload().await?;\n\n // clean up the internal pool of the provider node\n node.inner.pool.remove_transactions(vec![tx_hash1]);\n\n // inject tx2, make the node reorg and eventually generate `CanonStateNotification::Reorg` event\n // to propagate to the pool\n let _ = node.rpc.inject_tx(envelop2.encoded_2718().into()).await.unwrap();\n\n // build a payload based on tx2\n let payload2 = node.new_payload().await?;\n\n // submit payload1\n let block_hash1 = node.submit_payload(payload1).await?;\n\n node.update_forkchoice(genesis_hash, block_hash1).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Commit` event correctly, and finally\n // tx1 will be removed and tx2 is still in the pool\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_none() && txpool.get(&tx_hash2).is_some() {\n break;\n }\n }\n\n // submit payload2\n let block_hash2 = node.submit_payload(payload2).await?;\n\n node.update_forkchoice(genesis_hash, block_hash2).await?;\n\n loop {\n // wait for pool to process `CanonStateNotification::Reorg` event properly, and finally tx1\n // will be added back to the pool and tx2 will be removed.\n tokio::time::sleep(std::time::Duration::from_millis(20)).await;\n if txpool.get(&tx_hash1).is_some() && txpool.get(&tx_hash2).is_none() {\n break;\n }\n }\n\n Ok(())\n}\n\n// Test that the pool's maintenance task can correctly handle `CanonStateNotification::Commit`\n// events\n#[tokio::test]\nasync fn maintain_txpool_commit() -> eyre::Result<()> {\n reth_tracing::init_test_tracing();\n let runtime = Runtime::test();\n\n let txpool = Pool::new(\n OkValidator::default(),\n CoinbaseTipOrdering::default(),\n InMemoryBlobStore::default(),\n Default::default(),\n );\n\n // Directly generate a node to simulate various traits such as `StateProviderFactory` required\n // by the pool maintenance task\n let genesis: Genesis = serde_json::from_str(include_str!(\"../assets/genesis.json\")).unwrap();\n let chain_spec = Arc::new(\n ChainSpecBuilder::default()\n ", "nodeType": "Use"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "", "middle": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\n", "suffix": "use std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reach", "nodeType": "Use"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\n", "middle": "use std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n", "suffix": "\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap", "nodeType": "Use"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n", "middle": "/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n", "suffix": "\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!delet", "nodeType": "Struct"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n", "middle": "#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n", "suffix": "\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgres", "nodeType": "Struct"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\n", "middle": "impl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n", "suffix": "\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_e", "nodeType": "Impl"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n", "middle": " const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n", "suffix": "\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n ", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self ", "middle": "{\n Self { limit, deleted: 0 }\n }", "suffix": "\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n", "middle": " const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n", "suffix": "}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pr", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool ", "middle": "{\n self.deleted >= self.limit\n }", "suffix": "\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgre", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n", "middle": "#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n", "suffix": "\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not rese", "nodeType": "Struct"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\n", "middle": "impl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n", "suffix": "\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit", "nodeType": "Impl"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n", "middle": " fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n", "suffix": "\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_dele", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self ", "middle": "{\n Self { limit, start: Instant::now() }\n }", "suffix": "\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDe", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n", "middle": " fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n", "suffix": "}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n ", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool ", "middle": "{\n self.start.elapsed() > self.limit\n }", "suffix": "\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n", "middle": " pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n", "suffix": "\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denomin", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self ", "middle": "{\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }", "suffix": "\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimit", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n", "middle": " pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n", "suffix": "\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limi", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self ", "middle": "{\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }", "suffix": "\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not se", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n", "middle": " pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n", "suffix": "\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limi", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool ", "middle": "{\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }", "suffix": "\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted =", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n", "middle": " pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n", "suffix": "\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 1", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) ", "middle": "{\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }", "suffix": "\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n", "middle": " pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n", "suffix": "\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n ", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) ", "middle": "{\n self.increment_deleted_entries_count_by(1)\n }", "suffix": "\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n /", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n", "middle": " pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n", "suffix": "\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_ent", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option ", "middle": "{\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }", "suffix": "\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limite", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n", "middle": " pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n", "suffix": "\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment ", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option ", "middle": "{\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }", "suffix": "\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initia", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n", "middle": " pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n", "suffix": "\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing()", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self ", "middle": "{\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }", "suffix": "\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = Pr", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n", "middle": " pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n", "suffix": "\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n a", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool ", "middle": "{\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }", "suffix": "\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limi", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n", "middle": " pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n", "suffix": "\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::de", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool ", "middle": "{\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }", "suffix": "\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_e", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n", "middle": " pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n", "suffix": "\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n ", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason ", "middle": "{\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }", "suffix": "\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_li", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n", "middle": " pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n", "suffix": "}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_le", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress ", "middle": "{\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }", "suffix": "\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = ", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n", "middle": " use super::*;\n", "suffix": " use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleti", "nodeType": "Use"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "as started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n", "middle": " use std::thread::sleep;\n", "suffix": "\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);", "nodeType": "Use"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n", "middle": " fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entri", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() ", "middle": "{\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None)", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() ", "middle": "{\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": " (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() ", "middle": "{\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return ", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached,", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "use reth_prune_types::{PruneInterruptReason, PruneProgress};\nuse std::{\n num::NonZeroUsize,\n time::{Duration, Instant},\n};\n\n/// Limits a pruner run by either the number of entries (rows in the database) that can be deleted\n/// or the time it can run.\n#[derive(Debug, Clone, Default)]\npub struct PruneLimiter {\n /// Maximum entries (rows in the database) to delete from the database per run.\n deleted_entries_limit: Option,\n /// Maximum duration of one prune run.\n time_limit: Option,\n}\n\n#[derive(Debug, Clone)]\nstruct PruneDeletedEntriesLimit {\n /// Maximum entries (rows in the database) to delete from the database.\n limit: usize,\n /// Current number of entries (rows in the database) that have been deleted.\n deleted: usize,\n}\n\nimpl PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() ", "middle": "{\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "urating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() ", "middle": "{\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::de", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "rns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() ", "middle": "{\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_incre", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "PruneDeletedEntriesLimit {\n const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_de", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "const fn new(limit: usize) -> Self {\n Self { limit, deleted: 0 }\n }\n\n const fn is_limit_reached(&self) -> bool {\n self.deleted >= self.limit\n }\n}\n\n#[derive(Debug, Clone)]\nstruct PruneTimeLimit {\n /// Maximum duration of one prune run.\n limit: Duration,\n /// Time when the prune run has started.\n start: Instant,\n}\n\nimpl PruneTimeLimit {\n fn new(limit: Duration) -> Self {\n Self { limit, start: Instant::now() }\n }\n\n fn is_limit_reached(&self) -> bool {\n self.start.elapsed() > self.limit\n }\n}\n\nimpl PruneLimiter {\n /// Sets the limit on the number of deleted entries (rows in the database).\n /// If the limit was already set, it will be overwritten but the deleted count preserved.\n pub const fn set_deleted_entries_limit(mut self, limit: usize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() ", "middle": "{\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n ", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "leted_entries_limit.limit = limit;\n } else {\n self.deleted_entries_limit = Some(PruneDeletedEntriesLimit::new(limit));\n }\n\n self\n }\n\n /// Sets the limit on the number of deleted entries (rows in the database) to a biggest\n /// multiple of the given denominator that is smaller than the existing limit.\n ///\n /// If the limit wasn't set, does nothing.\n pub fn floor_deleted_entries_limit_to_multiple_of(mut self, denominator: NonZeroUsize) -> Self {\n if let Some(deleted_entries_limit) = self.deleted_entries_limit.as_mut() {\n deleted_entries_limit.limit =\n (deleted_entries_limit.limit / denominator) * denominator.get();\n }\n\n self\n }\n\n /// Returns `true` if the limit on the number of deleted entries (rows in the database) is\n /// reached.\n pub fn is_deleted_entries_limit_reached(&self) -> bool {\n self.deleted_entries_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Increments the number of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n", "suffix": "\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let de", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "mit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() ", "middle": "{\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }", "suffix": "\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let ", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ber of deleted entries by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n", "middle": " fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n", "suffix": "\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "by the given number.\n pub const fn increment_deleted_entries_count_by(&mut self, entries: usize) {\n if let Some(limit) = self.deleted_entries_limit.as_mut() {\n limit.deleted += entries;\n }\n }\n\n /// Increments the number of deleted entries by one.\n pub const fn increment_deleted_entries_count(&mut self) {\n self.increment_deleted_entries_count_by(1)\n }\n\n /// Returns the number of deleted entries left before the limit is reached.\n pub fn deleted_entries_limit_left(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit.saturating_sub(limit.deleted))\n }\n\n /// Returns the limit on the number of deleted entries (rows in the database).\n pub fn deleted_entries_limit(&self) -> Option {\n self.deleted_entries_limit.as_ref().map(|limit| limit.limit)\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() ", "middle": "{\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }", "suffix": "\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": ")\n }\n\n /// Sets the time limit.\n pub fn set_time_limit(mut self, limit: Duration) -> Self {\n self.time_limit = Some(PruneTimeLimit::new(limit));\n\n self\n }\n\n /// Returns `true` if time limit is reached.\n pub fn is_time_limit_reached(&self) -> bool {\n self.time_limit.as_ref().is_some_and(|limit| limit.is_limit_reached())\n }\n\n /// Returns `true` if any limit is reached.\n pub fn is_limit_reached(&self) -> bool {\n self.is_deleted_entries_limit_reached() || self.is_time_limit_reached()\n }\n\n /// Creates new [`PruneInterruptReason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n", "middle": " fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n", "suffix": "\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ched());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() ", "middle": "{\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }", "suffix": "\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limit", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ason`] based on the limiter's state.\n pub fn interrupt_reason(&self) -> PruneInterruptReason {\n if self.is_time_limit_reached() {\n PruneInterruptReason::Timeout\n } else if self.is_deleted_entries_limit_reached() {\n PruneInterruptReason::DeletedEntriesLimitReached\n } else {\n PruneInterruptReason::Unknown\n }\n }\n\n /// Creates new [`PruneProgress`].\n ///\n /// If `done == true`, returns [`PruneProgress::Finished`], otherwise\n /// [`PruneProgress::HasMoreData`] is returned with [`PruneInterruptReason`] according to the\n /// limiter's state.\n pub fn progress(&self, done: bool) -> PruneProgress {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n", "middle": " fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n", "suffix": "\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() ", "middle": "{\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }", "suffix": "\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n ", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": " {\n if done {\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n", "middle": " fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n", "suffix": "\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "\n PruneProgress::Finished\n } else {\n PruneProgress::HasMoreData(self.interrupt_reason())\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::thread::sleep;\n\n #[test]\n fn test_prune_deleted_entries_limit_initial_state() {\n let limit_tracker = PruneDeletedEntriesLimit::new(10);\n // Limit should be set properly\n assert_eq!(limit_tracker.limit, 10);\n // No entries should be deleted\n assert_eq!(limit_tracker.deleted, 0);\n assert!(!limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_deleted_entries_limit_is_limit_reached() {\n // Test when the deleted entries are less than the limit\n let mut limit_tracker = PruneDeletedEntriesLimit::new(5);\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() ", "middle": "{\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }", "suffix": "\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "it is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n", "middle": " fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n", "suffix": "\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_de", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": ";\n limit_tracker.deleted = 3;\n assert!(!limit_tracker.is_limit_reached());\n\n // Test when the deleted entries are equal to the limit\n limit_tracker.deleted = 5;\n assert!(limit_tracker.is_limit_reached());\n\n // Test when the deleted entries exceed the limit\n limit_tracker.deleted = 6;\n assert!(limit_tracker.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_initial_state() {\n let time_limit = PruneTimeLimit::new(Duration::from_secs(10));\n // The limit should be set correctly\n assert_eq!(time_limit.limit, Duration::from_secs(10));\n // The elapsed time should be very small right after creation\n assert!(time_limit.start.elapsed() < Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() ", "middle": "{\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }", "suffix": "\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "rt!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n", "middle": " fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n", "suffix": "\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "< Duration::from_secs(1));\n // Limit should not be reached initially\n assert!(!time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_prune_time_limit_is_limit_reached() {\n let time_limit = PruneTimeLimit::new(Duration::from_millis(50));\n\n // Simulate waiting for some time (less than the limit)\n std::thread::sleep(Duration::from_millis(30));\n assert!(!time_limit.is_limit_reached());\n\n // Simulate waiting for time greater than the limit\n std::thread::sleep(Duration::from_millis(30));\n assert!(time_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_initial_state() {\n let pruner = PruneLimiter::default().set_deleted_entries_limit(100);\n // The deleted_entries_limit should be set with the correct limit\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 100);\n // The deleted count should be initially zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n // The limit should not be reached initially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() ", "middle": "{\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }", "suffix": "\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ially\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_overwrite_existing() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(50);\n // Overwrite the existing limit\n pruner = pruner.set_deleted_entries_limit(200);\n\n assert!(pruner.deleted_entries_limit.is_some());\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n // Check that the limit has been overwritten correctly\n assert_eq!(deleted_entries_limit.limit, 200);\n // Deleted count should still be zero\n assert_eq!(deleted_entries_limit.deleted, 0);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_set_deleted_entries_limit_when_limit_is_reached() {\n let mut pruner = PruneLimiter::default().set_deleted_entries_limit(5);\n assert!(pruner.deleted_entries_limit.is_some());\n\n // Simulate deletion of entries on the actual limiter\n pruner.increment_deleted_entries_count_by(5);\n assert!(pruner.is_deleted_entries_limit_reached());\n\n // Overwrite the limit - deleted count is preserved (needed for cross-segment tracking)\n pruner = pruner.set_deleted_entries_limit(10);\n let deleted_entries_limit = pruner.deleted_entries_limit.unwrap();\n assert_eq!(deleted_entries_limit.limit, 10);\n // Deleted count is preserved, not reset\n assert_eq!(deleted_entries_limit.deleted, 5);\n assert!(!deleted_entries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n", "middle": " fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n", "suffix": "\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": " = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() ", "middle": "{\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }", "suffix": "\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "ntries_limit.is_limit_reached());\n }\n\n #[test]\n fn test_floor_deleted_entries_limit_to_multiple_of() {\n let limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n let denominator = NonZeroUsize::new(4).unwrap();\n\n // Floor limit to the largest multiple of 4 less than or equal to 15 (that is 12)\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 12);\n\n // Test when the limit is already a multiple of the denominator\n let limiter = PruneLimiter::default().set_deleted_entries_limit(16);\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(updated_limiter.deleted_entries_limit.unwrap().limit, 16);\n\n // Test when there's no limit set (should not panic)\n let limiter = PruneLimiter::default();\n let updated_limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert!(updated_limiter.deleted_entries_limit.is_none());\n }\n\n #[test]\n fn test_is_deleted_entries_limit_reached() {\n // Limit is not set, should return false\n let limiter = PruneLimiter::default();\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is set but not reached, should return false\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 5;\n // 5 entries deleted out of 10\n assert!(!limiter.is_deleted_entries_limit_reached());\n\n // Limit is reached, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 10;\n // 10 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n\n // Deleted entries exceed the limit, should return true\n limiter.deleted_entries_limit.as_mut().unwrap().deleted = 12;\n // 12 entries deleted out of 10\n assert!(limiter.is_deleted_entries_limit_reached());\n }\n\n #[test]\n fn test_increment_deleted_entries_count_by() {\n // Increment when no limit is set\n let mut limiter = PruneLimiter::default();\n limiter.increment_deleted_entries_count_by(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().map(|l| l.deleted), None); // Still None\n\n // Increment when limit is set\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 3); // Now 3 deleted\n\n // Increment again\n limiter.increment_deleted_entries_count_by(2);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 5); // Now 5 deleted\n }\n\n #[test]\n fn test_increment_deleted_entries_count() {\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 0); // Initially 0\n\n limiter.increment_deleted_entries_count(); // Increment by 1\n assert_eq!(limiter.deleted_entries_limit.as_ref().unwrap().deleted, 1); // Now 1\n }\n\n #[test]\n fn test_deleted_entries_limit_left() {\n // Test when limit is set and some entries are deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3); // Simulate 3 deleted entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7)); // 10 - 3 = 7\n\n // Test when no entries are deleted\n limiter = PruneLimiter::default().set_deleted_entries_limit(5);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(5)); // 5 - 0 = 5\n\n // Test when limit is reached\n limiter.increment_deleted_entries_count_by(5); // Simulate deleting 5 entries\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0)); // 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n", "middle": " fn test_deleted_entries_limit_left_saturation_and_normal() {\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/prune/prune/src/limiter.rs", "prefix": "/ 5 - 5 = 0\n\n // Test when limit is not set\n limiter = PruneLimiter::default(); // No limit set\n assert_eq!(limiter.deleted_entries_limit_left(), None); // Should be None\n }\n\n #[test]\n fn test_set_time_limit() {\n // Create a PruneLimiter instance with no time limit set\n let mut limiter = PruneLimiter::default();\n\n // Set a time limit of 5 seconds\n limiter = limiter.set_time_limit(Duration::new(5, 0));\n\n // Verify that the time limit is set correctly\n assert!(limiter.time_limit.is_some());\n let time_limit = limiter.time_limit.as_ref().unwrap();\n assert_eq!(time_limit.limit, Duration::new(5, 0));\n // Ensure the start time is recent\n assert!(time_limit.start.elapsed() < Duration::new(1, 0));\n }\n\n #[test]\n fn test_is_time_limit_reached() {\n // Create a PruneLimiter instance and set a time limit of 10 milliseconds\n let mut limiter = PruneLimiter::default();\n\n // Time limit should not be reached initially\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(!limiter.is_time_limit_reached(), \"Time limit should not be reached yet\");\n\n // Sleep for an additional 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_time_limit_reached(), \"Time limit should be reached now\");\n }\n\n #[test]\n fn test_is_limit_reached() {\n // Create a PruneLimiter instance\n let mut limiter = PruneLimiter::default();\n\n // Test when no limits are set\n assert!(!limiter.is_limit_reached(), \"Limit should not be reached with no limits set\");\n\n // Set a deleted entries limit\n limiter = limiter.set_deleted_entries_limit(5);\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when deleted entries are less than limit\"\n );\n\n // Increment deleted entries count to reach the limit\n limiter.increment_deleted_entries_count_by(5);\n assert!(\n limiter.is_limit_reached(),\n \"Limit should be reached when deleted entries equal the limit\"\n );\n\n // Reset the limiter\n limiter = PruneLimiter::default();\n\n // Set a time limit and check\n limiter = limiter.set_time_limit(Duration::new(0, 10_000_000)); // 10 milliseconds\n\n // Sleep for 5 milliseconds (less than the time limit)\n sleep(Duration::new(0, 5_000_000)); // 5 milliseconds\n assert!(\n !limiter.is_limit_reached(),\n \"Limit should not be reached when time limit not reached\"\n );\n\n // Sleep for another 10 milliseconds (totaling 15 milliseconds)\n sleep(Duration::new(0, 10_000_000)); // 10 milliseconds\n assert!(limiter.is_limit_reached(), \"Limit should be reached when time limit is reached\");\n }\n\n #[test]\n fn test_deleted_entries_limit_left_saturation_and_normal() ", "middle": "{\n // less than limit \u2192 no saturation\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(7));\n\n // equal to limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(3);\n limiter.increment_deleted_entries_count_by(3);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // overrun past limit \u2192 saturates to 0\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(10);\n limiter.increment_deleted_entries_count_by(12);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via set \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(20);\n limiter.increment_deleted_entries_count_by(15);\n let limiter = limiter.set_deleted_entries_limit(10);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n\n // lowering limit via floor \u2192 saturates to 0 if below deleted\n let mut limiter = PruneLimiter::default().set_deleted_entries_limit(15);\n limiter.increment_deleted_entries_count_by(14);\n let denominator = NonZeroUsize::new(8).unwrap();\n let limiter = limiter.floor_deleted_entries_limit_to_multiple_of(denominator);\n assert_eq!(limiter.deleted_entries_limit_left(), Some(0));\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\n", "middle": "use alloy_eips::{eip2124::Head, BlockNumHash};\n", "suffix": "use futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: component", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\n", "middle": "use futures::future;\n", "suffix": "use reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\n", "middle": "use reth_chain_state::ForkChoiceSubscriptions;\n", "suffix": "use reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n ", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\n", "middle": "use reth_chainspec::EthChainSpec;\n", "suffix": "use reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\n", "middle": "use reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\n", "suffix": "use reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target:", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\n", "middle": "use reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\n", "suffix": "use reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n ", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\n", "middle": "use reth_provider::CanonStateSubscriptions;\n", "suffix": "use reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\n", "middle": "use reth_tracing::tracing::{debug, info};\n", "suffix": "use std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\n", "middle": "use std::{fmt, fmt::Debug};\n", "suffix": "use tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\n", "middle": "use tracing::Instrument;\n", "suffix": "\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\n", "middle": "use crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n", "suffix": "\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n ", "nodeType": "Use"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n", "middle": "/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n", "suffix": "\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n", "middle": " pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n", "suffix": "\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self ", "middle": "{\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }", "suffix": "\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n", "middle": " pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n", "suffix": "\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self ", "middle": "{\n self.wal_blocks_warning = threshold;\n self\n }", "suffix": "\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n", "middle": " pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n", "suffix": "\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self ", "middle": "{\n self.capacity = capacity;\n self\n }", "suffix": "\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .awai", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": "//! Support for launching execution extensions.\n\nuse alloy_eips::{eip2124::Head, BlockNumHash};\nuse futures::future;\nuse reth_chain_state::ForkChoiceSubscriptions;\nuse reth_chainspec::EthChainSpec;\nuse reth_exex::{\n ExExContext, ExExHandle, ExExManager, ExExManagerHandle, ExExNotificationSource, Wal,\n DEFAULT_EXEX_MANAGER_CAPACITY, DEFAULT_WAL_BLOCKS_WARNING,\n};\nuse reth_node_api::{FullNodeComponents, NodeTypes, PrimitivesTy};\nuse reth_provider::CanonStateSubscriptions;\nuse reth_tracing::tracing::{debug, info};\nuse std::{fmt, fmt::Debug};\nuse tracing::Instrument;\n\nuse crate::{common::WithConfigs, exex::BoxedLaunchExEx};\n\n/// Can launch execution extensions.\npub struct ExExLauncher {\n head: Head,\n extensions: Vec<(String, Box>)>,\n components: Node,\n config_container: WithConfigs<::ChainSpec>,\n /// The threshold for the number of blocks in the WAL before emitting a warning.\n wal_blocks_warning: usize,\n /// The max notification buffer capacity for the ExEx manager.\n capacity: usize,\n}\n\nimpl ExExLauncher {\n /// Create a new `ExExLauncher` with the given extensions.\n pub const fn new(\n head: Head,\n components: Node,\n extensions: Vec<(String, Box>)>,\n config_container: WithConfigs<::ChainSpec>,\n ) -> Self {\n Self {\n head,\n extensions,\n components,\n config_container,\n wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,\n capacity: DEFAULT_EXEX_MANAGER_CAPACITY,\n }\n }\n\n /// Sets the threshold for the number of blocks in the WAL before emitting a warning.\n ///\n /// For L2 chains with faster block times, this value should be increased proportionally\n /// to avoid excessive warnings. For example, a chain with 2-second block times might use\n /// a value 6x higher than the default (768 instead of 128).\n pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {\n self.wal_blocks_warning = threshold;\n self\n }\n\n /// Sets the max notification buffer capacity for the [`ExExManager`].\n pub const fn with_capacity(mut self, capacity: usize) -> Self {\n self.capacity = capacity;\n self\n }\n\n /// Launches all execution extensions.\n ///\n /// Spawns all extensions and returns the handle to the exex manager if any extensions are\n /// installed.\n pub async fn launch(\n self,\n ) -> eyre::Result>>> {\n let Self { head, extensions, components, config_container, wal_blocks_warning, capacity } =\n self;\n let head = BlockNumHash::new(head.number, head.hash);\n\n if extensions.is_empty() {\n // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\n", "middle": "impl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n}\n", "suffix": "", "nodeType": "Impl"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": " // nothing to launch\n return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n", "middle": " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/launch/exex.rs", "prefix": " return Ok(None)\n }\n\n info!(target: \"reth::cli\", \"Loading ExEx Write-Ahead Log...\");\n let exex_wal = Wal::new(\n config_container\n .config\n .datadir\n .clone()\n .resolve_datadir(config_container.config.chain.chain())\n .exex_wal(),\n )?;\n\n let mut exex_handles = Vec::with_capacity(extensions.len());\n let mut exexes = Vec::with_capacity(extensions.len());\n\n for (id, exex) in extensions {\n // create a new exex handle\n let (handle, events, notifications) = ExExHandle::new(\n id.clone(),\n head,\n components.provider().clone(),\n components.evm_config().clone(),\n exex_wal.handle(),\n );\n exex_handles.push(handle);\n\n // create the launch context for the exex\n let context = ExExContext {\n head,\n config: config_container.config.clone(),\n reth_config: config_container.toml_config.clone(),\n components: components.clone(),\n events,\n notifications,\n };\n\n let executor = components.task_executor().clone();\n exexes.push(async move {\n debug!(target: \"reth::cli\", id, \"spawning exex\");\n let span = reth_tracing::tracing::info_span!(\"exex\", id);\n\n // init the exex\n let exex = exex.launch(context).instrument(span.clone()).await?;\n\n // spawn it as a crit task\n executor.spawn_critical_task(\n \"exex\",\n async move {\n info!(target: \"reth::cli\", \"ExEx started\");\n match exex.await {\n Ok(_) => panic!(\"ExEx {id} finished. ExExes should run indefinitely\"),\n Err(err) => panic!(\"ExEx {id} crashed: {err}\"),\n }\n }\n .instrument(span),\n );\n\n Ok::<(), eyre::Error>(())\n });\n }\n\n future::try_join_all(exexes).await?;\n\n // spawn exex manager\n debug!(target: \"reth::cli\", \"spawning exex manager\");\n let exex_manager = ExExManager::new(\n components.provider().clone(),\n exex_handles,\n capacity,\n exex_wal,\n components.provider().finalized_block_stream(),\n )\n .with_wal_blocks_warning(wal_blocks_warning);\n let exex_manager_handle = exex_manager.handle();\n components.task_executor().spawn_critical_task(\"exex manager\", async move {\n exex_manager.await.expect(\"exex manager crashed\");\n });\n\n // send notifications from the blockchain tree to exex manager\n let mut canon_state_notifications = components.provider().subscribe_to_canonical_state();\n let mut handle = exex_manager_handle.clone();\n components.task_executor().spawn_critical_task(\n \"exex manager blockchain tree notifications\",\n async move {\n while let Ok(notification) = canon_state_notifications.recv().await {\n handle\n .send_async(ExExNotificationSource::BlockchainTree, notification.into())\n .await\n .expect(\"blockchain tree notification could not be sent to exex manager\");\n }\n },\n );\n\n info!(target: \"reth::cli\", \"ExEx Manager started\");\n\n Ok(Some(exex_manager_handle))\n }\n}\n\nimpl Debug for ExExLauncher {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result ", "middle": "{\n f.debug_struct(\"ExExLauncher\")\n .field(\"head\", &self.head)\n .field(\"extensions\", &self.extensions.iter().map(|(id, _)| id).collect::>())\n .field(\"components\", &\"...\")\n .field(\"config_container\", &self.config_container)\n .field(\"wal_blocks_warning\", &self.wal_blocks_warning)\n .finish()\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "", "middle": "use std::fmt;\n", "suffix": "\nuse reth_node_api::FullNodeComponents;\nuse reth_node_core::exit::NodeExitFuture;\n\nuse crate::{node::FullNode, rpc::RethRpcAddOns};\n\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n pub async fn wait_for_node_exit(self) -> eyre::Result<()> {\n self.node_exit_future.await\n }\n}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "use std::fmt;\n\n", "middle": "use reth_node_api::FullNodeComponents;\n", "suffix": "use reth_node_core::exit::NodeExitFuture;\n\nuse crate::{node::FullNode, rpc::RethRpcAddOns};\n\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n pub async fn wait_for_node_exit(self) -> eyre::Result<()> {\n self.node_exit_future.await\n }\n}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "use std::fmt;\n\nuse reth_node_api::FullNodeComponents;\n", "middle": "use reth_node_core::exit::NodeExitFuture;\n", "suffix": "\nuse crate::{node::FullNode, rpc::RethRpcAddOns};\n\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n pub async fn wait_for_node_exit(self) -> eyre::Result<()> {\n self.node_exit_future.await\n }\n}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "use std::fmt;\n\nuse reth_node_api::FullNodeComponents;\nuse reth_node_core::exit::NodeExitFuture;\n\n", "middle": "use crate::{node::FullNode, rpc::RethRpcAddOns};\n", "suffix": "\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n pub async fn wait_for_node_exit(self) -> eyre::Result<()> {\n self.node_exit_future.await\n }\n}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "use std::fmt;\n\nuse reth_node_api::FullNodeComponents;\nuse reth_node_core::exit::NodeExitFuture;\n\nuse crate::{node::FullNode, rpc::RethRpcAddOns};\n\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n", "middle": " pub async fn wait_for_node_exit(self) -> eyre::Result<()> {\n self.node_exit_future.await\n }\n", "suffix": "}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/node/builder/src/handle.rs", "prefix": "use std::fmt;\n\nuse reth_node_api::FullNodeComponents;\nuse reth_node_core::exit::NodeExitFuture;\n\nuse crate::{node::FullNode, rpc::RethRpcAddOns};\n\n/// A Handle to the launched node.\n#[must_use = \"Needs to await the node exit future\"]\npub struct NodeHandle> {\n /// All node components.\n pub node: FullNode,\n /// The exit future of the node.\n pub node_exit_future: NodeExitFuture,\n}\n\nimpl NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n /// Waits for the node to exit, if it was configured to exit.\n pub async fn wait_for_node_exit(self) -> eyre::Result<()> ", "middle": "{\n self.node_exit_future.await\n }", "suffix": "\n}\n\nimpl fmt::Debug for NodeHandle\nwhere\n Node: FullNodeComponents,\n AddOns: RethRpcAddOns,\n{\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"NodeHandle\")\n .field(\"node\", &\"...\")\n .field(\"node_exit_future\", &self.node_exit_future)\n .finish()\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\n", "middle": "use crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\n", "suffix": "use futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVa", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\n", "middle": "use futures::{FutureExt, StreamExt};\n", "suffix": "use pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let n", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\n", "middle": "use pin_project::pin_project;\n", "suffix": "use reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| pee", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\n", "middle": "use reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\n", "suffix": "use reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n n", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\n", "middle": "use reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\n", "suffix": "use reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = ", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\n", "middle": "use reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\n", "suffix": "use reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(pee", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\n", "middle": "use reth_evm_ethereum::EthEvmConfig;\n", "suffix": "use reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to ", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\n", "middle": "use reth_metrics::common::mpsc::memory_bounded_channel;\n", "suffix": "use reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\n", "middle": "use reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\n", "suffix": "use reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n ///", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\n", "middle": "use reth_network_peers::PeerId;\n", "suffix": "use reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics o", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\n", "middle": "use reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\n", "suffix": "use reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\n", "middle": "use reth_tasks::Runtime;\n", "suffix": "use reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\n", "middle": "use reth_tokio_util::EventStream;\n", "suffix": "use reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each pee", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\n", "middle": "use reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\n", "suffix": "use secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\n", "middle": "use secp256k1::SecretKey;\n", "suffix": "use std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a ", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\n", "middle": "use std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\n", "suffix": "use tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\n", "middle": "use tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n", "suffix": "\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n ", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\n", "middle": "use crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n", "suffix": "\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n", "nodeType": "Use"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n", "middle": "/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n", "suffix": "\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n ", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\n", "middle": "impl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n", "suffix": "\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n", "middle": " pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n", "suffix": "\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self ", "middle": "{\n Self::try_create_with(num_peers, provider).await.unwrap()\n }", "suffix": "\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n", "middle": " pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n", "suffix": "\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction man", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result ", "middle": "{\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }", "suffix": "\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n fo", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n", "middle": " pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n", "suffix": "}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> ", "middle": "{\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }", "suffix": "\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\n", "middle": "impl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n", "suffix": "\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(nu", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n", "middle": " pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n", "suffix": "\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n R", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] ", "middle": "{\n &mut self.peers\n }", "suffix": "\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n", "middle": " pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n", "suffix": "\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] ", "middle": "{\n &self.peers\n }", "suffix": "\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_p", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n", "middle": " pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n", "suffix": "\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer ", "middle": "{\n self.peers.remove(index)\n }", "suffix": "\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primit", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ting purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n", "middle": " pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n", "suffix": "\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + Header", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "TH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ ", "middle": "{\n self.peers.iter_mut()\n }", "suffix": "\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Cl", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "rotocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n", "middle": " pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n", "suffix": "\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ ", "middle": "{\n self.peers.iter()\n }", "suffix": "\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_add", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "use reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n", "middle": " pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n", "suffix": "\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "rdforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> ", "middle": "{\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }", "suffix": "\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n le", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n", "middle": " pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n", "suffix": "\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ ", "middle": "{\n self.peers.iter().map(|p| p.handle())\n }", "suffix": "\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHan", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n", "middle": " pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n", "suffix": "\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "r,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n ", "middle": "{\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }", "suffix": "\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n", "middle": " pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n", "suffix": "\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpx", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n ", "middle": "{\n self.peers.iter().for_each(f)\n }", "suffix": "\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n", "middle": " pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n", "suffix": "}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n ", "middle": "{\n self.peers.iter_mut().for_each(f)\n }", "suffix": "\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\n", "middle": "impl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n", "suffix": "\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n", "middle": " pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n", "suffix": "\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> ", "middle": "{\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }", "suffix": "\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n", "middle": " pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n", "suffix": "\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> ", "middle": "{\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }", "suffix": "\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.cl", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "//! A network implementation for testing purposes.\n\nuse crate::{\n builder::ETH_REQUEST_CHANNEL_CAPACITY,\n error::NetworkError,\n eth_requests::EthRequestHandler,\n protocol::IntoRlpxSubProtocol,\n transactions::{\n config::{StrictEthAnnouncementFilter, TransactionPropagationKind},\n policy::NetworkPolicies,\n TransactionsHandle, TransactionsManager, TransactionsManagerConfig,\n },\n NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n", "middle": " pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n", "suffix": "}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clon", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "-> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> ", "middle": "{\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }", "suffix": "\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "tworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, PeersConfig,\n};\nuse futures::{FutureExt, StreamExt};\nuse pin_project::pin_project;\nuse reth_chainspec::{ChainSpecProvider, EthereumHardforks, Hardforks};\nuse reth_eth_wire::{\n protocol::Protocol, DisconnectReason, EthNetworkPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\n", "middle": "impl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n", "suffix": "\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "workPrimitives, HelloMessageWithProtocols,\n};\nuse reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};\nuse reth_evm_ethereum::EthEvmConfig;\nuse reth_metrics::common::mpsc::memory_bounded_channel;\nuse reth_network_api::{\n events::{PeerEvent, SessionInfo},\n test_utils::{PeersHandle, PeersHandleProvider},\n NetworkEvent, NetworkEventListenerProvider, NetworkInfo, Peers,\n};\nuse reth_network_peers::PeerId;\nuse reth_storage_api::{\n noop::NoopProvider, BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n", "middle": " pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n", "suffix": "}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle ", "middle": "{\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }", "suffix": "\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\n", "middle": "impl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n", "suffix": "\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " BalProvider, BlockReader, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n", "middle": " pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n", "suffix": "\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "r, BlockReaderIdExt, HeaderProvider,\n StateProviderFactory,\n};\nuse reth_tasks::Runtime;\nuse reth_tokio_util::EventStream;\nuse reth_transaction_pool::{\n blobstore::InMemoryBlobStore,\n test_utils::{TestPool, TestPoolBuilder},\n EthTransactionPool, PoolTransaction, TransactionPool, TransactionValidationTaskExecutor,\n};\nuse secp256k1::SecretKey;\nuse std::{\n fmt,\n future::Future,\n net::{Ipv4Addr, SocketAddr, SocketAddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self ", "middle": "{\n Self::try_create(num_peers).await.unwrap()\n }", "suffix": "\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_b", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n", "middle": " pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n", "suffix": "\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.ad", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ly a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result ", "middle": "{\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }", "suffix": "\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "AddrV4},\n pin::Pin,\n task::{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n", "middle": " pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n", "suffix": "}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clon", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ":{Context, Poll},\n};\nuse tokio::{\n sync::{mpsc::channel, oneshot},\n task::JoinHandle,\n};\n\nuse crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> ", "middle": "{\n self.add_peer_with_config(Default::default()).await\n }", "suffix": "\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ckReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\n", "middle": "impl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n", "suffix": "\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n", "middle": " fn default() -> Self {\n Self { peers: Vec::new() }\n }\n", "suffix": "}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The addres", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ts::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES;\n\n/// A test network consisting of multiple peers.\npub struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider
\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self ", "middle": "{\n Self { peers: Vec::new() }\n }", "suffix": "\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transact", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " struct Testnet {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\n", "middle": "impl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n", "suffix": "\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "> {\n /// All running peers in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n", "middle": " fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n", "suffix": "}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "in the network.\n peers: Vec>,\n}\n\n// === impl Testnet ===\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static + ChainSpecProvider,\n{\n /// Same as [`Self::try_create_with`] but panics on error\n pub async fn create_with(num_peers: usize, provider: C) -> Self {\n Self::try_create_with(num_peers, provider).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers and the provider.\n pub async fn try_create_with(num_peers: usize, provider: C) -> Result {\n let mut this = Self { peers: Vec::with_capacity(num_peers) };\n for _ in 0..num_peers {\n let config = PeerConfig::new(provider.clone());\n this.add_peer_with_config(config).await?;\n }\n Ok(this)\n }\n\n /// Extend the list of peers with new peers that are configured with each of the given\n /// [`PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result ", "middle": "{\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }", "suffix": "\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: Block", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ransactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\n", "middle": "impl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n", "suffix": "\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n", "middle": " fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n", "suffix": "}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "r_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll ", "middle": "{\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }", "suffix": "\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "PeerConfig`]s.\n pub async fn extend_peer_with_config(\n &mut self,\n configs: impl IntoIterator>,\n ) -> Result<(), NetworkError> {\n let peers = configs.into_iter().map(|c| c.launch()).collect::>();\n let peers = futures::future::join_all(peers).await;\n for peer in peers {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n", "middle": "/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n", "suffix": "\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n ", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "et\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\n", "middle": "impl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n", "suffix": "\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, reque", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " {\n self.peers.push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n", "middle": " pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n", "suffix": "\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "push(peer?);\n }\n Ok(())\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Return a mutable slice of all peers.\n pub fn peers_mut(&mut self) -> &mut [Peer] {\n &mut self.peers\n }\n\n /// Return a slice of all peers.\n pub fn peers(&self) -> &[Peer] {\n &self.peers\n }\n\n /// Remove a peer from the [`Testnet`] and return it.\n ///\n /// # Panics\n /// If the index is out of bounds.\n pub fn remove_peer(&mut self, index: usize) -> Peer {\n self.peers.remove(index)\n }\n\n /// Return a mutable iterator over all peers.\n pub fn peers_iter_mut(&mut self) -> impl Iterator> + '_ {\n self.peers.iter_mut()\n }\n\n /// Return an iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet ", "middle": "{\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }", "suffix": "\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "one(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n", "middle": " pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n", "suffix": "\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] ", "middle": "{\n &self.peers\n }", "suffix": "\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManag", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "n iterator over all peers.\n pub fn peers_iter(&self) -> impl Iterator> + '_ {\n self.peers.iter()\n }\n\n /// Add a peer to the [`Testnet`] with the given [`PeerConfig`].\n pub async fn add_peer_with_config(\n &mut self,\n config: PeerConfig,\n ) -> Result<(), NetworkError> {\n let PeerConfig { config, client, secret_key } = config;\n\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n self.peers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n", "middle": " pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n", "suffix": "}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn e", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ctionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) ", "middle": "{\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }", "suffix": "\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n networ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ers.push(peer);\n Ok(())\n }\n\n /// Returns all handles to the networks\n pub fn handles(&self) -> impl Iterator> + '_ {\n self.peers.iter().map(|p| p.handle())\n }\n\n /// Maps the pool of each peer with the given closure\n pub fn map_pool(self, f: F) -> Testnet\n where\n F: Fn(Peer) -> Peer,\n P: TransactionPool,\n {\n Testnet { peers: self.peers.into_iter().map(f).collect() }\n }\n\n /// Apply a closure on each peer\n pub fn for_each(&self, f: F)\n where\n F: Fn(&Peer),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n", "middle": "/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n", "suffix": "\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n ", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "rs).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n", "middle": " pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n", "suffix": "\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounde", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize ", "middle": "{\n self.network.num_connected_peers()\n }", "suffix": "\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Pool>),\n {\n self.peers.iter().for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n", "middle": " pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n", "suffix": "\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ".for_each(f)\n }\n\n /// Apply a closure on each peer\n pub fn for_each_mut(&mut self, f: F)\n where\n F: FnMut(&mut Peer),\n {\n self.peers.iter_mut().for_each(f)\n }\n}\n\nimpl Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) ", "middle": "{\n self.network.add_rlpx_sub_protocol(protocol);\n }", "suffix": "\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ", Pool> Testnet\nwhere\n C: ChainSpecProvider\n + StateProviderFactory\n + BlockReaderIdExt\n + HeaderProvider

\n + Clone\n + 'static,\n Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n", "middle": " pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n", "suffix": "\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle ", "middle": "{\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }", "suffix": "\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Pool: TransactionPool,\n{\n /// Installs an eth pool on each peer\n pub fn with_eth_pool(\n self,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n", "middle": " pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n", "suffix": "\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKe", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr ", "middle": "{\n self.network.local_addr()\n }", "suffix": "\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "estnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n", "middle": " pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n", "suffix": "\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "actionPool> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n peer.map_transactions_manager(EthTransactionPool::eth_pool(\n pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId ", "middle": "{\n *self.network.peer_id()\n }", "suffix": "\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "eceipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n", "middle": " pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n", "suffix": "\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPool", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ",\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager ", "middle": "{\n &mut self.network\n }", "suffix": "\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n", "middle": " pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n", "suffix": "\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n R", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle ", "middle": "{\n self.network.handle().clone()\n }", "suffix": "\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitive", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " pool,\n blob_store,\n Default::default(),\n ))\n })\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config\n pub fn with_eth_pool_config(\n self,\n tx_manager_config: TransactionsManagerConfig,\n ) -> Testnet> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n", "middle": " pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n", "suffix": "\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> ", "middle": "{\n self.pool.as_ref()\n }", "suffix": "\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + '", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n", "middle": " pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n", "suffix": "\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx:", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "bStore, EthEvmConfig>> {\n self.with_eth_pool_config_and_policy(tx_manager_config, Default::default())\n }\n\n /// Installs an eth pool on each peer with custom transaction manager config and policy.\n pub fn with_eth_pool_config_and_policy(\n self,\n tx_manager_config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Testnet> {\n self.map_pool(|peer| {\n let blob_store = InMemoryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n ", "middle": "{\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }", "suffix": "\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBu", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ryBlobStore::default();\n let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n", "middle": " pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n", "suffix": "\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// T", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " let pool = TransactionValidationTaskExecutor::eth(\n peer.client.clone(),\n EthEvmConfig::mainnet(),\n blob_store.clone(),\n Runtime::test(),\n );\n\n peer.map_transactions_manager_with(\n EthTransactionPool::eth_pool(pool, blob_store, Default::default()),\n tx_manager_config.clone(),\n policy,\n )\n })\n }\n}\n\nimpl Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Clone\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) ", "middle": "{\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }", "suffix": "\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await es", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "x + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n", "middle": " pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n", "suffix": "\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`Netwo", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n /// Spawns the testnet to a separate task\n pub fn spawn(self) -> TestnetHandle {\n let (tx, rx) = oneshot::channel::>();\n let peers = self.peers.iter().map(|peer| peer.peer_handle()).collect::>();\n let mut net = self;\n let handle = tokio::task::spawn(async move {\n let mut tx = None;\n tokio::select! {\n _ = &mut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n ", "middle": "{\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }", "suffix": "\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next eve", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "l = TestPool> {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n", "middle": " pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n", "suffix": "\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ut net => {}\n inc = rx => {\n tx = inc.ok();\n }\n }\n if let Some(tx) = tx {\n let _ = tx.send(net);\n }\n });\n\n TestnetHandle { _handle: handle, peers, terminate: tx }\n }\n}\n\nimpl Testnet {\n /// Same as [`Self::try_create`] but panics on error\n pub async fn create(num_peers: usize) -> Self {\n Self::try_create(num_peers).await.unwrap()\n }\n\n /// Creates a new [`Testnet`] with the given number of peers\n pub async fn try_create(num_peers: usize) -> Result {\n let mut this = Self::default();\n\n this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?;\n Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n ", "middle": "{\n self.map_transactions_manager_with(pool, config, Default::default())\n }", "suffix": "\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n", "middle": " pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n", "suffix": "}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(clie", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Ok(this)\n }\n\n /// Add a peer to the [`Testnet`]\n pub async fn add_peer(&mut self) -> Result<(), NetworkError> {\n self.add_peer_with_config(Default::default()).await\n }\n}\n\nimpl Default for Testnet {\n fn default() -> Self {\n Self { peers: Vec::new() }\n }\n}\n\nimpl fmt::Debug for Testnet {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n f.debug_struct(\"Testnet {{}}\").finish_non_exhaustive()\n }\n}\n\nimpl Future for Testnet\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n ", "middle": "{\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }", "suffix": "\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\n", "middle": "impl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n", "suffix": "\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n ", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "mitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n", "middle": " pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n", "suffix": "}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n //", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) ", "middle": "{\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }", "suffix": "\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next e", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " this = self.get_mut();\n for peer in &mut this.peers {\n let _ = peer.poll_unpin(cx);\n }\n Poll::Pending\n }\n}\n\n/// A handle to a [`Testnet`] that can be shared.\n#[derive(Debug)]\npub struct TestnetHandle {\n _handle: JoinHandle<()>,\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\n", "middle": "impl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n", "suffix": "\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id)", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ",\n peers: Vec>,\n terminate: oneshot::Sender>>,\n}\n\n// === impl TestnetHandle ===\n\nimpl TestnetHandle {\n /// Terminates the task and returns the [`Testnet`] back.\n pub async fn terminate(self) -> Testnet {\n let (tx, rx) = oneshot::channel();\n self.terminate.send(tx).unwrap();\n rx.await.unwrap()\n }\n\n /// Returns the [`PeerHandle`]s of this [`Testnet`].\n pub fn peers(&self) -> &[PeerHandle] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n", "middle": " fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n", "suffix": "}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll ", "middle": "{\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }", "suffix": "\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(So", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n", "middle": "/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n", "suffix": "\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "] {\n &self.peers\n }\n\n /// Connects all peers with each other.\n ///\n /// This establishes sessions concurrently between all peers.\n ///\n /// Returns once all sessions are established.\n pub async fn connect_peers(&self) {\n if self.peers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n", "middle": "/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n", "suffix": "\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ur = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\n", "middle": "impl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n", "suffix": "\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ers.len() < 2 {\n return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n", "middle": " pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n", "suffix": "\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " return\n }\n\n // add an event stream for _each_ peer\n let streams =\n self.peers.iter().map(|handle| NetworkEventStream::new(handle.event_listener()));\n\n // add all peers to each other\n for (idx, handle) in self.peers.iter().enumerate().take(self.peers.len() - 1) {\n for idx in (idx + 1)..self.peers.len() {\n let neighbour = &self.peers[idx];\n handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId ", "middle": "{\n self.network.peer_id()\n }", "suffix": "\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n", "middle": " pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n", "suffix": "\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle ", "middle": "{\n self.network.peers_handle()\n }", "suffix": "\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n", "middle": " pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n", "suffix": "\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason })", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr ", "middle": "{\n self.network.local_addr()\n }", "suffix": "\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " handle.network.add_peer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n", "middle": " pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n", "suffix": "\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "eer(*neighbour.peer_id(), neighbour.local_addr());\n }\n }\n\n // await all sessions to be established\n let num_sessions_per_peer = self.peers.len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream ", "middle": "{\n self.network.event_listener()\n }", "suffix": "\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n", "middle": " pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n", "suffix": "\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ".len() - 1;\n let fut = streams.into_iter().map(|mut stream| async move {\n stream.take_session_established(num_sessions_per_peer).await\n });\n\n futures::future::join_all(fut).await;\n }\n}\n\n/// A peer in the [`Testnet`].\n#[pin_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> ", "middle": "{\n self.transactions.as_ref()\n }", "suffix": "\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n", "middle": " pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n", "suffix": "\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n ", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "sactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> ", "middle": "{\n self.pool.as_ref()\n }", "suffix": "\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "in_project]\n#[derive(Debug)]\npub struct Peer {\n #[pin]\n network: NetworkManager,\n #[pin]\n request_handler: Option>,\n #[pin]\n transactions_manager: Option>,\n pool: Option,\n client: C,\n secret_key: SecretKey,\n}\n\n// === impl Peer ===\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n", "middle": " pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n", "suffix": "}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "ig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle ", "middle": "{\n &self.network\n }", "suffix": "\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\n", "middle": "impl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n", "suffix": "\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ": BlockReader + HeaderProvider + Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n", "middle": " pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n", "suffix": "\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "+ Clone + 'static,\n Pool: TransactionPool,\n{\n /// Returns the number of connected peers.\n pub fn num_peers(&self) -> usize {\n self.network.num_connected_peers()\n }\n\n /// Adds an additional protocol handler to the peer.\n pub fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {\n self.network.add_rlpx_sub_protocol(protocol);\n }\n\n /// Returns a handle to the peer's network.\n pub fn peer_handle(&self) -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> ", "middle": "{\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }", "suffix": "\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " -> PeerHandle {\n PeerHandle {\n network: self.network.handle().clone(),\n pool: self.pool.clone(),\n transactions: self.transactions_manager.as_ref().map(|mgr| mgr.handle()),\n }\n }\n\n /// The address that listens for incoming connections.\n pub const fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// The [`PeerId`] of this peer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n", "middle": " pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n", "suffix": "\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n ", "middle": "{\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }", "suffix": "\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) =", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "eer.\n pub fn peer_id(&self) -> PeerId {\n *self.network.peer_id()\n }\n\n /// Returns mutable access to the network.\n pub const fn network_mut(&mut self) -> &mut NetworkManager {\n &mut self.network\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub fn handle(&self) -> NetworkHandle {\n self.network.handle().clone()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Set a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n", "middle": " pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n", "suffix": "\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "/ Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n ", "middle": "{\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }", "suffix": "\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n ", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n", "middle": " pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n", "suffix": "\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n //", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "t a new request handler that's connected to the peer's network\n pub fn install_request_handler(&mut self)\n where\n C: BalProvider,\n {\n let (tx, rx) = channel(ETH_REQUEST_CHANNEL_CAPACITY);\n self.network.set_eth_request_handler(tx);\n let peers = self.network.peers_handle();\n let request_handler = EthRequestHandler::new(self.client.clone(), peers, rx);\n self.request_handler = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n ", "middle": "{\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }", "suffix": "\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "r = Some(request_handler);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n", "middle": " fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n", "suffix": "}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "/// Set a new transactions manager that's connected to the peer's network\n pub fn install_transactions_manager(&mut self, pool: Pool) {\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder ", "middle": "{\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }", "suffix": "\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": ",\n \"test_tx_channel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\n", "middle": "impl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n", "suffix": "\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "fig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n", "middle": " fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n", "suffix": "}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "nnel\",\n );\n self.network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self ", "middle": "{\n Self::new(NoopProvider::default())\n }", "suffix": "\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " self.handle(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n self.transactions_manager = Some(transactions_manager);\n self.pool = Some(pool);\n }\n\n /// Set a new transactions manager that's connected to the peer's network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n", "middle": "/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n", "suffix": "\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "'s network\n pub fn map_transactions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n", "middle": " pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n", "suffix": "\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "actions_manager

(self, pool: P) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self ", "middle": "{\n Self { inner }\n }", "suffix": "\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n", "middle": " pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n", "suffix": "\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " \"test_tx_channel\",\n );\n network.set_transactions(tx);\n let transactions_manager = TransactionsManager::new(\n network.handle().clone(),\n pool.clone(),\n rx,\n TransactionsManagerConfig::default(),\n );\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n\n /// Map transactions manager with custom config\n pub fn map_transactions_manager_with_config

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n ) -> Peer\n where\n P: TransactionPool,\n {\n self.map_transactions_manager_with(pool, config, Default::default())\n }\n\n /// Map transactions manager with custom config and the given policy.\n pub fn map_transactions_manager_with

(\n self,\n pool: P,\n config: TransactionsManagerConfig,\n policy: TransactionPropagationKind,\n ) -> Peer\n where\n P: TransactionPool,\n {\n let Self { mut network, request_handler, client, secret_key, .. } = self;\n let (tx, rx) = memory_bounded_channel(\n DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,\n \"test_tx_channel\",\n );\n network.set_transactions(tx);\n\n let announcement_policy = StrictEthAnnouncementFilter::default();\n let policies = NetworkPolicies::new(policy, announcement_policy);\n\n let transactions_manager = TransactionsManager::with_policy(\n network.handle().clone(),\n pool.clone(),\n rx,\n config,\n policies,\n );\n\n Peer {\n network,\n request_handler,\n transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> ", "middle": "{\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }", "suffix": "\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "f()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n", "middle": " pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n", "suffix": "\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "stPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option ", "middle": "{\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }", "suffix": "\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n", "middle": " pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n", "suffix": "\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "} = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec ", "middle": "{\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }", "suffix": "\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "lowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n", "middle": " pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n", "suffix": "\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " transactions_manager: Some(transactions_manager),\n pool: Some(pool),\n client,\n secret_key,\n }\n }\n}\n\nimpl Peer\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Installs a new [`TestPool`]\n pub fn install_test_pool(&mut self) {\n self.install_transactions_manager(TestPoolBuilder::default().into())\n }\n}\n\nimpl Future for Peer\nwhere\n C: BlockReader<\n Block = reth_ethereum_primitives::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option ", "middle": "{\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }", "suffix": "\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "::Block,\n Receipt = reth_ethereum_primitives::Receipt,\n Header = alloy_consensus::Header,\n > + HeaderProvider\n + BalProvider\n + Unpin\n + 'static,\n Pool: TransactionPool<\n Transaction: PoolTransaction<\n Consensus = TransactionSigned,\n Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n", "middle": " pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n", "suffix": "\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option ", "middle": "{\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }", "suffix": "\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": " Pooled = PooledTransactionVariant,\n >,\n > + Unpin\n + 'static,\n{\n type Output = ();\n\n fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll {\n let this = self.project();\n\n if let Some(request) = this.request_handler.as_pin_mut() {\n let _ = request.poll(cx);\n }\n\n if let Some(tx_manager) = this.transactions_manager.as_pin_mut() {\n let _ = tx_manager.poll(cx);\n }\n\n this.network.poll(cx)\n }\n}\n\n/// A helper config for setting up the reth networking stack.\n#[derive(Debug)]\npub struct PeerConfig {\n config: NetworkConfig,\n client: C,\n secret_key: SecretKey,\n}\n\n/// A handle to a peer in the [`Testnet`].\n#[derive(Debug)]\npub struct PeerHandle {\n network: NetworkHandle,\n transactions: Option>,\n pool: Option,\n}\n\n// === impl PeerHandle ===\n\nimpl PeerHandle {\n /// Returns the [`PeerId`] used in the network.\n pub fn peer_id(&self) -> &PeerId {\n self.network.peer_id()\n }\n\n /// Returns the [`PeersHandle`] from the network.\n pub fn peer_handle(&self) -> &PeersHandle {\n self.network.peers_handle()\n }\n\n /// Returns the local socket as configured for the network.\n pub fn local_addr(&self) -> SocketAddr {\n self.network.local_addr()\n }\n\n /// Creates a new [`NetworkEvent`] listener channel.\n pub fn event_listener(&self) -> EventStream {\n self.network.event_listener()\n }\n\n /// Returns the [`TransactionsHandle`] of this peer.\n pub const fn transactions(&self) -> Option<&TransactionsHandle> {\n self.transactions.as_ref()\n }\n\n /// Returns the [`TestPool`] of this peer.\n pub const fn pool(&self) -> Option<&Pool> {\n self.pool.as_ref()\n }\n\n /// Returns the [`NetworkHandle`] of this peer.\n pub const fn network(&self) -> &NetworkHandle {\n &self.network\n }\n}\n\n// === impl PeerConfig ===\n\nimpl PeerConfig\nwhere\n C: BlockReader + HeaderProvider + Clone + 'static,\n{\n /// Launches the network and returns the [Peer] that manages it\n pub async fn launch(self) -> Result, NetworkError> {\n let Self { config, client, secret_key } = self;\n let network = NetworkManager::new(config).await?;\n let peer = Peer {\n network,\n client,\n secret_key,\n request_handler: None,\n transactions_manager: None,\n pool: None,\n };\n Ok(peer)\n }\n\n /// Initialize the network with a random secret key, allowing the devp2p and discovery to bind\n /// to any available IP and port.\n pub fn new(client: C) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given secret key, allowing devp2p and discovery to bind any\n /// available IP and port.\n pub fn with_secret_key(client: C, secret_key: SecretKey) -> Self\n where\n C: ChainSpecProvider,\n {\n let config = Self::network_config_builder(secret_key).build(client.clone());\n Self { config, client, secret_key }\n }\n\n /// Initialize the network with a given capabilities.\n pub fn with_protocols(client: C, protocols: impl IntoIterator) -> Self\n where\n C: ChainSpecProvider,\n {\n let secret_key = SecretKey::new(&mut rand_08::thread_rng());\n\n let builder = Self::network_config_builder(secret_key);\n let hello_message =\n HelloMessageWithProtocols::builder(builder.get_peer_id()).protocols(protocols).build();\n let config = builder.hello_message(hello_message).build(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n", "middle": " pub async fn peer_removed(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/net/network/src/test_utils/testnet.rs", "prefix": "d(client.clone());\n\n Self { config, client, secret_key }\n }\n\n fn network_config_builder(secret_key: SecretKey) -> NetworkConfigBuilder {\n NetworkConfigBuilder::new(secret_key, Runtime::test())\n .listener_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .discovery_addr(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)))\n .disable_dns_discovery()\n .disable_discv4_discovery()\n .peer_config(PeersConfig::test())\n }\n}\n\nimpl Default for PeerConfig {\n fn default() -> Self {\n Self::new(NoopProvider::default())\n }\n}\n\n/// A helper type to await network events\n///\n/// This makes it easier to await established connections\n#[derive(Debug)]\npub struct NetworkEventStream {\n inner: EventStream,\n}\n\n// === impl NetworkEventStream ===\n\nimpl NetworkEventStream {\n /// Create a new [`NetworkEventStream`] from the given network event receiver stream.\n pub const fn new(inner: EventStream) -> Self {\n Self { inner }\n }\n\n /// Awaits the next event for a session to be closed\n pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> {\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev {\n return Some((peer_id, reason))\n }\n }\n None\n }\n\n /// Awaits the next event for an established session\n pub async fn next_session_established(&mut self) -> Option {\n while let Some(ev) = self.inner.next().await {\n match ev {\n NetworkEvent::ActivePeerSession { info, .. } |\n NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {\n return Some(info.peer_id)\n }\n _ => {}\n }\n }\n None\n }\n\n /// Awaits the next `num` events for an established session\n pub async fn take_session_established(&mut self, mut num: usize) -> Vec {\n if num == 0 {\n return Vec::new();\n }\n let mut peers = Vec::with_capacity(num);\n while let Some(ev) = self.inner.next().await {\n if let NetworkEvent::ActivePeerSession { info: SessionInfo { peer_id, .. }, .. } = ev {\n peers.push(peer_id);\n num -= 1;\n if num == 0 {\n return peers;\n }\n }\n }\n peers\n }\n\n /// Ensures that the first two events are a [`NetworkEvent::Peer`] and\n /// [`PeerEvent::PeerAdded`][`NetworkEvent::ActivePeerSession`], returning the [`PeerId`] of the\n /// established session.\n pub async fn peer_added_and_established(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n match self.inner.next().await {\n Some(NetworkEvent::ActivePeerSession {\n info: SessionInfo { peer_id: peer_id2, .. },\n ..\n }) => {\n debug_assert_eq!(\n peer_id, peer_id2,\n \"PeerAdded peer_id {peer_id} does not match SessionEstablished peer_id {peer_id2}\"\n );\n Some(peer_id)\n }\n _ => None,\n }\n }\n\n /// Awaits the next event for a peer added.\n pub async fn peer_added(&mut self) -> Option {\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerAdded(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }\n\n /// Awaits the next event for a peer removed.\n pub async fn peer_removed(&mut self) -> Option ", "middle": "{\n let peer_id = match self.inner.next().await {\n Some(NetworkEvent::Peer(PeerEvent::PeerRemoved(peer_id))) => peer_id,\n _ => return None,\n };\n\n Some(peer_id)\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/transaction-pool/tests/it/evict.rs", "prefix": "//! Transaction pool eviction tests.\n\n", "middle": "use alloy_consensus::Transaction;\n", "suffix": "use alloy_eips::eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE};\nuse alloy_primitives::{Address, B256};\nuse rand::distr::Uniform;\nuse reth_transaction_pool::{\n error::PoolErrorKind,\n test_utils::{\n MockFeeRange, MockTransactionDistribution, MockTransactionRatio, TestPool, TestPoolBuilder,\n },\n AddedTransactionOutcome, BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin,\n TransactionPool, TransactionPoolExt,\n};\n\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn only_blobs_eviction() {\n // This test checks that blob transactions can be inserted into the pool, and at each step the\n // blob pool can be truncated to the correct size\n\n // set the pool limits to something small\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n queued_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n basefee_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n blob_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n pool.set_block_info(block_info);\n\n // this is how many times the test will regenerate transactions and insert them into the pool\n let total_txs = 1000;\n\n // If we have a wide size range we can cover cases both where we have a lot of small txs and a\n // lot of large txs\n let size_range = 10..1100;\n\n // create mock tx distribution, 100% blobs\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 0,\n dynamic_fee_pct: 0,\n blob_pct: 100,\n access_list_pct: 0,\n };\n\n // Vary the amount of senders\n let senders = [1, 10, 100, total_txs];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n\n // split the total txs into the amount of senders\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // start the fees at zero, some transactions will be underpriced\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n priority_fee: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n // we need to set the max fee to at least the min protocol base fee, or transactions\n // generated could be rejected\n max_fee: Uniform::try_from(\n MIN_PROTOCOL_BASE_FEE as u128..(block_info.pending_basefee as u128 + 2000),\n )\n .unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n // use a random sender, create the tx set\n let sender = Address::random();\n let set = distribution.tx_set(sender, nonce_range.clone(), &mut rand::rng());\n\n let set = set.into_vec();\n\n // ensure that the first nonce is 0\n assert_eq!(set[0].nonce(), 0);\n\n // and finally insert it into the pool\n let results = pool.add_transactions(TransactionOrigin::External, set).await;\n for (i, result) in results.iter().enumerate() {\n match result {\n Ok(AddedTransactionOutcome { hash, .. }) => {\n println!(\"\u2705 Inserted tx into pool with h", "nodeType": "Use"} {"filePath": "crates/transaction-pool/tests/it/evict.rs", "prefix": "//! Transaction pool eviction tests.\n\nuse alloy_consensus::Transaction;\n", "middle": "use alloy_eips::eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE};\n", "suffix": "use alloy_primitives::{Address, B256};\nuse rand::distr::Uniform;\nuse reth_transaction_pool::{\n error::PoolErrorKind,\n test_utils::{\n MockFeeRange, MockTransactionDistribution, MockTransactionRatio, TestPool, TestPoolBuilder,\n },\n AddedTransactionOutcome, BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin,\n TransactionPool, TransactionPoolExt,\n};\n\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn only_blobs_eviction() {\n // This test checks that blob transactions can be inserted into the pool, and at each step the\n // blob pool can be truncated to the correct size\n\n // set the pool limits to something small\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n queued_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n basefee_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n blob_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n pool.set_block_info(block_info);\n\n // this is how many times the test will regenerate transactions and insert them into the pool\n let total_txs = 1000;\n\n // If we have a wide size range we can cover cases both where we have a lot of small txs and a\n // lot of large txs\n let size_range = 10..1100;\n\n // create mock tx distribution, 100% blobs\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 0,\n dynamic_fee_pct: 0,\n blob_pct: 100,\n access_list_pct: 0,\n };\n\n // Vary the amount of senders\n let senders = [1, 10, 100, total_txs];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n\n // split the total txs into the amount of senders\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // start the fees at zero, some transactions will be underpriced\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n priority_fee: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n // we need to set the max fee to at least the min protocol base fee, or transactions\n // generated could be rejected\n max_fee: Uniform::try_from(\n MIN_PROTOCOL_BASE_FEE as u128..(block_info.pending_basefee as u128 + 2000),\n )\n .unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n // use a random sender, create the tx set\n let sender = Address::random();\n let set = distribution.tx_set(sender, nonce_range.clone(), &mut rand::rng());\n\n let set = set.into_vec();\n\n // ensure that the first nonce is 0\n assert_eq!(set[0].nonce(), 0);\n\n // and finally insert it into the pool\n let results = pool.add_transactions(TransactionOrigin::External, set).await;\n for (i, result) in results.iter().enumerate() {\n match result {\n Ok(AddedTransactionOutcome { hash, .. }) => {\n println!(\"\u2705 Inserted tx into pool with hash: {hash}\");\n }\n ", "nodeType": "Use"} {"filePath": "crates/transaction-pool/tests/it/evict.rs", "prefix": "//! Transaction pool eviction tests.\n\nuse alloy_consensus::Transaction;\nuse alloy_eips::eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE};\n", "middle": "use alloy_primitives::{Address, B256};\n", "suffix": "use rand::distr::Uniform;\nuse reth_transaction_pool::{\n error::PoolErrorKind,\n test_utils::{\n MockFeeRange, MockTransactionDistribution, MockTransactionRatio, TestPool, TestPoolBuilder,\n },\n AddedTransactionOutcome, BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin,\n TransactionPool, TransactionPoolExt,\n};\n\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn only_blobs_eviction() {\n // This test checks that blob transactions can be inserted into the pool, and at each step the\n // blob pool can be truncated to the correct size\n\n // set the pool limits to something small\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n queued_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n basefee_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n blob_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n pool.set_block_info(block_info);\n\n // this is how many times the test will regenerate transactions and insert them into the pool\n let total_txs = 1000;\n\n // If we have a wide size range we can cover cases both where we have a lot of small txs and a\n // lot of large txs\n let size_range = 10..1100;\n\n // create mock tx distribution, 100% blobs\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 0,\n dynamic_fee_pct: 0,\n blob_pct: 100,\n access_list_pct: 0,\n };\n\n // Vary the amount of senders\n let senders = [1, 10, 100, total_txs];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n\n // split the total txs into the amount of senders\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // start the fees at zero, some transactions will be underpriced\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n priority_fee: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n // we need to set the max fee to at least the min protocol base fee, or transactions\n // generated could be rejected\n max_fee: Uniform::try_from(\n MIN_PROTOCOL_BASE_FEE as u128..(block_info.pending_basefee as u128 + 2000),\n )\n .unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n // use a random sender, create the tx set\n let sender = Address::random();\n let set = distribution.tx_set(sender, nonce_range.clone(), &mut rand::rng());\n\n let set = set.into_vec();\n\n // ensure that the first nonce is 0\n assert_eq!(set[0].nonce(), 0);\n\n // and finally insert it into the pool\n let results = pool.add_transactions(TransactionOrigin::External, set).await;\n for (i, result) in results.iter().enumerate() {\n match result {\n Ok(AddedTransactionOutcome { hash, .. }) => {\n println!(\"\u2705 Inserted tx into pool with hash: {hash}\");\n }\n Err(e) => {\n match e.kind {\n ", "nodeType": "Use"} {"filePath": "crates/transaction-pool/tests/it/evict.rs", "prefix": "//! Transaction pool eviction tests.\n\nuse alloy_consensus::Transaction;\nuse alloy_eips::eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE};\nuse alloy_primitives::{Address, B256};\n", "middle": "use rand::distr::Uniform;\n", "suffix": "use reth_transaction_pool::{\n error::PoolErrorKind,\n test_utils::{\n MockFeeRange, MockTransactionDistribution, MockTransactionRatio, TestPool, TestPoolBuilder,\n },\n AddedTransactionOutcome, BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin,\n TransactionPool, TransactionPoolExt,\n};\n\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn only_blobs_eviction() {\n // This test checks that blob transactions can be inserted into the pool, and at each step the\n // blob pool can be truncated to the correct size\n\n // set the pool limits to something small\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n queued_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n basefee_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n blob_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n pool.set_block_info(block_info);\n\n // this is how many times the test will regenerate transactions and insert them into the pool\n let total_txs = 1000;\n\n // If we have a wide size range we can cover cases both where we have a lot of small txs and a\n // lot of large txs\n let size_range = 10..1100;\n\n // create mock tx distribution, 100% blobs\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 0,\n dynamic_fee_pct: 0,\n blob_pct: 100,\n access_list_pct: 0,\n };\n\n // Vary the amount of senders\n let senders = [1, 10, 100, total_txs];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n\n // split the total txs into the amount of senders\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // start the fees at zero, some transactions will be underpriced\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n priority_fee: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n // we need to set the max fee to at least the min protocol base fee, or transactions\n // generated could be rejected\n max_fee: Uniform::try_from(\n MIN_PROTOCOL_BASE_FEE as u128..(block_info.pending_basefee as u128 + 2000),\n )\n .unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n // use a random sender, create the tx set\n let sender = Address::random();\n let set = distribution.tx_set(sender, nonce_range.clone(), &mut rand::rng());\n\n let set = set.into_vec();\n\n // ensure that the first nonce is 0\n assert_eq!(set[0].nonce(), 0);\n\n // and finally insert it into the pool\n let results = pool.add_transactions(TransactionOrigin::External, set).await;\n for (i, result) in results.iter().enumerate() {\n match result {\n Ok(AddedTransactionOutcome { hash, .. }) => {\n println!(\"\u2705 Inserted tx into pool with hash: {hash}\");\n }\n Err(e) => {\n match e.kind {\n PoolErrorKind::DiscardedOnInsert => {\n println!(\"\u2705 Discarded tx on insert, like we should have\");\n }\n PoolErrorKind::SpammerExceededCapacity(addr) => {\n // ensure the address is the same as the sender\n assert_eq!(addr, sender);\n\n // ensure that this is only returned when the sender is over the\n // pool limit per account\n assert!(\n i + 1 >= pool_config.max_account_slots,\n \"Spammer exceeded capacity, but it shouldn't have. Max accounts slots: {}, current txs by sender: {}\",\n pool_config.max_account_slots,\n i + 1\n );\n // at this point we know that the sender has been limited, so we\n // keep going\n }\n _ => {\n panic!(\"Failed to insert tx into pool with unexpected error: {e}\");\n }\n }\n }\n }\n }\n\n // after every insert, ensure that it's under the pool limits\n assert!(!pool.is_exceeded());\n }\n }\n}\n\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn mixed_eviction() {\n // This test checks that many transaction types can be inserted into the pool. The fees need\n // to be set so that the transactions will actually pass validation. Transactions here do not\n // have nonce gaps.\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 20, max_size: 2000 },\n queued_limit: SubPoolLimit { max_txs: 20, max_size: 2000 },\n basefee_limit: SubPoolLimit { max_txs: 20, max_size: 2000 },\n blob_limit: SubPoolLimit { max_txs: 20, max_size: 2000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(20),\n };\n pool.set_block_info(block_info);\n\n let total_txs = 100;\n let size_range = 10..1100;\n\n // Adjust the ratios to include a mix of transaction types\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 25,\n dynamic_fee_pct: 25,\n blob_pct: 25,\n access_list_pct: 25,\n };\n\n let senders = [1, 5, 10];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // Make sure transactions are not immediately rejected\n let min_gas_price = block_info.pending_basefee as u128 + 1;\n let min_priority_fee = 1u128;\n let min_max_fee = block_info.pending_basefee as u128 + 10;\n\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(min_gas_price..(min_gas_price + 1000)).unwrap(),\n priority_fee: Uniform::try_from(min_priority_fee..(min_priority_fee + 1000)).unwrap(),\n max_fee: Uniform::try_from(min_max_fee..(min_max_fee + 2000)).unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n let sender = Address::random();\n let set = distribution.tx_set_non_con", "nodeType": "Use"} {"filePath": "crates/transaction-pool/tests/it/evict.rs", "prefix": "//! Transaction pool eviction tests.\n\nuse alloy_consensus::Transaction;\nuse alloy_eips::eip1559::{ETHEREUM_BLOCK_GAS_LIMIT_30M, MIN_PROTOCOL_BASE_FEE};\nuse alloy_primitives::{Address, B256};\nuse rand::distr::Uniform;\n", "middle": "use reth_transaction_pool::{\n error::PoolErrorKind,\n test_utils::{\n MockFeeRange, MockTransactionDistribution, MockTransactionRatio, TestPool, TestPoolBuilder,\n },\n AddedTransactionOutcome, BlockInfo, PoolConfig, SubPoolLimit, TransactionOrigin,\n TransactionPool, TransactionPoolExt,\n};\n", "suffix": "\n#[tokio::test(flavor = \"multi_thread\")]\nasync fn only_blobs_eviction() {\n // This test checks that blob transactions can be inserted into the pool, and at each step the\n // blob pool can be truncated to the correct size\n\n // set the pool limits to something small\n let pool_config = PoolConfig {\n pending_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n queued_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n basefee_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n blob_limit: SubPoolLimit { max_txs: 10, max_size: 1000 },\n ..Default::default()\n };\n\n let pool: TestPool = TestPoolBuilder::default().with_config(pool_config.clone()).into();\n let block_info = BlockInfo {\n block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M,\n last_seen_block_hash: B256::ZERO,\n last_seen_block_number: 0,\n pending_basefee: 10,\n pending_blob_fee: Some(10),\n };\n pool.set_block_info(block_info);\n\n // this is how many times the test will regenerate transactions and insert them into the pool\n let total_txs = 1000;\n\n // If we have a wide size range we can cover cases both where we have a lot of small txs and a\n // lot of large txs\n let size_range = 10..1100;\n\n // create mock tx distribution, 100% blobs\n let tx_ratio = MockTransactionRatio {\n legacy_pct: 0,\n dynamic_fee_pct: 0,\n blob_pct: 100,\n access_list_pct: 0,\n };\n\n // Vary the amount of senders\n let senders = [1, 10, 100, total_txs];\n for sender_amt in &senders {\n let gas_limit_range = 100_000..1_000_000;\n\n // split the total txs into the amount of senders\n let txs_per_sender = total_txs / sender_amt;\n let nonce_range = 0..txs_per_sender;\n let pending_blob_fee = block_info.pending_blob_fee.unwrap();\n\n // start the fees at zero, some transactions will be underpriced\n let fee_range = MockFeeRange {\n gas_price: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n priority_fee: Uniform::try_from(0u128..(block_info.pending_basefee as u128 + 1000))\n .unwrap(),\n // we need to set the max fee to at least the min protocol base fee, or transactions\n // generated could be rejected\n max_fee: Uniform::try_from(\n MIN_PROTOCOL_BASE_FEE as u128..(block_info.pending_basefee as u128 + 2000),\n )\n .unwrap(),\n max_fee_blob: Uniform::try_from(pending_blob_fee..(pending_blob_fee + 1000)).unwrap(),\n };\n\n let distribution = MockTransactionDistribution::new(\n tx_ratio.clone(),\n fee_range,\n gas_limit_range,\n size_range.clone(),\n );\n\n for _ in 0..*sender_amt {\n // use a random sender, create the tx set\n let sender = Address::random();\n let set = distribution.tx_set(sender, nonce_range.clone(), &mut rand::rng());\n\n let set = set.into_vec();\n\n // ensure that the first nonce is 0\n assert_eq!(set[0].nonce(), 0);\n\n // and finally insert it into the pool\n let results = pool.add_transactions(TransactionOrigin::External, set).await;\n for (i, result) in results.iter().enumerate() {\n match result {\n Ok(AddedTransactionOutcome { hash, .. }) => {\n println!(\"\u2705 Inserted tx into pool with hash: {hash}\");\n }\n Err(e) => {\n match e.kind {\n PoolErrorKind::DiscardedOnInsert => {\n println!(\"\u2705 Discarded tx on insert, like we should have\");\n }\n ", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "", "middle": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\n", "suffix": "use alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\n", "middle": "use alloy_primitives::{Address, B256, U256};\n", "suffix": "use core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn st", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\n", "middle": "use core::ops::{Deref, DerefMut};\n", "suffix": "use reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, inde", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\n", "middle": "use reth_primitives_traits::Account;\n", "suffix": "use reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\n", "middle": "use reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\n", "suffix": "use reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Re", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\n", "middle": "use reth_storage_errors::provider::{ProviderError, ProviderResult};\n", "suffix": "use revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\n", "middle": "use revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n", "suffix": "\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Use"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n", "middle": " fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n", "suffix": "\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Addr", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> ", "middle": "{\n ::basic_account(self, address)\n }", "suffix": "\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n", "middle": " fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n", "suffix": "\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n ", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> ", "middle": "{\n ::block_hash(self, number)\n }", "suffix": "\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a g", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n", "middle": " fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n", "suffix": "\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> ", "middle": "{\n ::bytecode_by_hash(self, code_hash)\n }", "suffix": "\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the b", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n", "middle": " fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n", "suffix": "}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> ", "middle": "{\n ::storage(self, account, storage_key)\n }", "suffix": "\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n", "middle": "/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n", "suffix": "\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Struct"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\n", "middle": "impl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n", "suffix": "\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n", "middle": " pub const fn new(db: DB) -> Self {\n Self(db)\n }\n", "suffix": "\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self ", "middle": "{\n Self(db)\n }", "suffix": "\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n", "middle": " pub fn into_inner(self) -> DB {\n self.0\n }\n", "suffix": "}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB ", "middle": "{\n self.0\n }", "suffix": "\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\n", "middle": "impl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n", "suffix": "\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n", "middle": " fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n", "suffix": "}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result ", "middle": "{\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }", "suffix": "\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\n", "middle": "impl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n", "suffix": "\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n", "middle": " fn as_ref(&self) -> &DB {\n self\n }\n", "suffix": "}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB ", "middle": "{\n self\n }", "suffix": "\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\n", "middle": "impl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n", "suffix": "\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n", "middle": " fn deref(&self) -> &Self::Target {\n &self.0\n }\n", "suffix": "}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target ", "middle": "{\n &self.0\n }", "suffix": "\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\n", "middle": "impl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n", "suffix": "\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Impl"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n", "middle": " fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n", "suffix": "}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target ", "middle": "{\n &mut self.0\n }", "suffix": "\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n", "middle": " fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n", "suffix": "\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> ", "middle": "{\n self.basic_ref(address)\n }", "suffix": "\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n", "middle": " fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n", "suffix": "\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result ", "middle": "{\n self.code_by_hash_ref(code_hash)\n }", "suffix": "\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": " reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n", "middle": " fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n", "suffix": "\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result ", "middle": "{\n self.storage_ref(address, index)\n }", "suffix": "\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n", "middle": " fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n", "suffix": "}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result ", "middle": "{\n self.block_hash_ref(number)\n }", "suffix": "\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n", "middle": " fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n", "suffix": "\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> ", "middle": "{\n Ok(self.basic_account(&address)?.map(Into::into))\n }", "suffix": "\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "age_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n", "middle": " fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n", "suffix": "\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result ", "middle": "{\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }", "suffix": "\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n", "middle": " fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n", "suffix": "\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result ", "middle": "{\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }", "suffix": "\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n}\n", "nodeType": "FunctionBody"} {"filePath": "crates/revm/src/database.rs", "prefix": "use crate::primitives::alloy_primitives::{BlockNumber, StorageKey, StorageValue};\nuse alloy_primitives::{Address, B256, U256};\nuse core::ops::{Deref, DerefMut};\nuse reth_primitives_traits::Account;\nuse reth_storage_api::{AccountReader, BlockHashReader, BytecodeReader, StateProvider};\nuse reth_storage_errors::provider::{ProviderError, ProviderResult};\nuse revm::{bytecode::Bytecode, state::AccountInfo, Database, DatabaseRef};\n\n/// A helper trait responsible for providing state necessary for EVM execution.\n///\n/// This serves as the data layer for [`Database`].\npub trait EvmStateProvider {\n /// Get basic account information.\n ///\n /// Returns [`None`] if the account doesn't exist.\n fn basic_account(&self, address: &Address) -> ProviderResult>;\n\n /// Get the hash of the block with the given number. Returns [`None`] if no block with this\n /// number exists.\n fn block_hash(&self, number: BlockNumber) -> ProviderResult>;\n\n /// Get account code by hash.\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult>;\n\n /// Get storage of the given account.\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult>;\n}\n\n// Blanket implementation of EvmStateProvider for any type that implements StateProvider.\nimpl EvmStateProvider for T {\n fn basic_account(&self, address: &Address) -> ProviderResult> {\n ::basic_account(self, address)\n }\n\n fn block_hash(&self, number: BlockNumber) -> ProviderResult> {\n ::block_hash(self, number)\n }\n\n fn bytecode_by_hash(\n &self,\n code_hash: &B256,\n ) -> ProviderResult> {\n ::bytecode_by_hash(self, code_hash)\n }\n\n fn storage(\n &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n", "middle": " fn block_hash_ref(&self, number: u64) -> Result {\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }\n", "suffix": "}\n", "nodeType": "Function"} {"filePath": "crates/revm/src/database.rs", "prefix": " &self,\n account: Address,\n storage_key: StorageKey,\n ) -> ProviderResult> {\n ::storage(self, account, storage_key)\n }\n}\n\n/// A [Database] and [`DatabaseRef`] implementation that uses [`EvmStateProvider`] as the underlying\n/// data source.\n#[derive(Clone)]\npub struct StateProviderDatabase(pub DB);\n\nimpl StateProviderDatabase {\n /// Create new State with generic `StateProvider`.\n pub const fn new(db: DB) -> Self {\n Self(db)\n }\n\n /// Consume State and return inner `StateProvider`.\n pub fn into_inner(self) -> DB {\n self.0\n }\n}\n\nimpl core::fmt::Debug for StateProviderDatabase {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"StateProviderDatabase\").finish_non_exhaustive()\n }\n}\n\nimpl AsRef for StateProviderDatabase {\n fn as_ref(&self) -> &DB {\n self\n }\n}\n\nimpl Deref for StateProviderDatabase {\n type Target = DB;\n\n fn deref(&self) -> &Self::Target {\n &self.0\n }\n}\n\nimpl DerefMut for StateProviderDatabase {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.0\n }\n}\n\nimpl Database for StateProviderDatabase {\n type Error = ProviderError;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic(&mut self, address: Address) -> Result, Self::Error> {\n self.basic_ref(address)\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash(&mut self, code_hash: B256) -> Result {\n self.code_by_hash_ref(code_hash)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage(&mut self, address: Address, index: U256) -> Result {\n self.storage_ref(address, index)\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n /// Note: It safely casts the `number` to `u64`.\n fn block_hash(&mut self, number: u64) -> Result {\n self.block_hash_ref(number)\n }\n}\n\nimpl DatabaseRef for StateProviderDatabase {\n type Error = ::Error;\n\n /// Retrieves basic account information for a given address.\n ///\n /// Returns `Ok` with `Some(AccountInfo)` if the account exists,\n /// `None` if it doesn't, or an error if encountered.\n fn basic_ref(&self, address: Address) -> Result, Self::Error> {\n Ok(self.basic_account(&address)?.map(Into::into))\n }\n\n /// Retrieves the bytecode associated with a given code hash.\n ///\n /// Returns `Ok` with the bytecode if found, or the default bytecode otherwise.\n fn code_by_hash_ref(&self, code_hash: B256) -> Result {\n Ok(self.bytecode_by_hash(&code_hash)?.unwrap_or_default().0)\n }\n\n /// Retrieves the storage value at a specific index for a given address.\n ///\n /// Returns `Ok` with the storage value, or the default value if not found.\n fn storage_ref(&self, address: Address, index: U256) -> Result {\n Ok(self.0.storage(address, B256::new(index.to_be_bytes()))?.unwrap_or_default())\n }\n\n /// Retrieves the block hash for a given block number.\n ///\n /// Returns `Ok` with the block hash if found, or the default hash otherwise.\n fn block_hash_ref(&self, number: u64) -> Result ", "middle": "{\n // Get the block hash or default hash with an attempt to convert U256 block number to u64\n Ok(self.0.block_hash(number)?.unwrap_or_default())\n }", "suffix": "\n}\n", "nodeType": "FunctionBody"}