replace lru with schnellru (#14539)

This commit is contained in:
Qinxuan Chen
2023-07-10 05:24:23 +08:00
committed by GitHub
parent 6dd625d568
commit 6d2c1ed719
11 changed files with 58 additions and 71 deletions
@@ -26,8 +26,8 @@ use codec::{Decode, Encode};
use futures::{channel::oneshot, stream::StreamExt};
use libp2p::PeerId;
use log::debug;
use lru::LruCache;
use prost::Message;
use schnellru::{ByLength, LruMap};
use sc_client_api::BlockBackend;
use sc_network::{
@@ -44,7 +44,6 @@ use sp_runtime::{
use std::{
cmp::min,
hash::{Hash, Hasher},
num::NonZeroUsize,
sync::Arc,
time::Duration,
};
@@ -137,7 +136,7 @@ pub struct BlockRequestHandler<B: BlockT, Client> {
/// Maps from request to number of times we have seen this request.
///
/// This is used to check if a peer is spamming us with the same request.
seen_requests: LruCache<SeenRequestsKey<B>, SeenRequestsValue>,
seen_requests: LruMap<SeenRequestsKey<B>, SeenRequestsValue>,
}
impl<B, Client> BlockRequestHandler<B, Client>
@@ -167,9 +166,8 @@ where
);
protocol_config.inbound_queue = Some(tx);
let capacity =
NonZeroUsize::new(num_peer_hint.max(1) * 2).expect("cache capacity is not zero");
let seen_requests = LruCache::new(capacity);
let capacity = ByLength::new(num_peer_hint.max(1) as u32 * 2);
let seen_requests = LruMap::new(capacity);
(Self { client, request_receiver, seen_requests }, protocol_config)
}
@@ -236,7 +234,7 @@ where
.difference(BlockAttributes::HEADER | BlockAttributes::JUSTIFICATION)
.is_empty();
match self.seen_requests.get_mut(&key) {
match self.seen_requests.get(&key) {
Some(SeenRequestsValue::First) => {},
Some(SeenRequestsValue::Fulfilled(ref mut requests)) => {
*requests = requests.saturating_add(1);
@@ -250,7 +248,7 @@ where
}
},
None => {
self.seen_requests.put(key.clone(), SeenRequestsValue::First);
self.seen_requests.insert(key.clone(), SeenRequestsValue::First);
},
}
@@ -277,7 +275,7 @@ where
.iter()
.any(|b| !b.header.is_empty() || !b.body.is_empty() || b.is_empty_justification)
{
if let Some(value) = self.seen_requests.get_mut(&key) {
if let Some(value) = self.seen_requests.get(&key) {
// If this is the first time we have processed this request, we need to change
// it to `Fulfilled`.
if let SeenRequestsValue::First = value {