mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-06-21 13:51:33 +00:00
chore(gossipsub): remove deprecated items
Removes deprecated items from gossipsub and make certain modules crate-private. Related https://github.com/libp2p/rust-libp2p/issues/3647. Pull-Request: #3862.
This commit is contained in:
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -2516,7 +2516,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"sha2 0.10.6",
|
"sha2 0.10.6",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"thiserror",
|
|
||||||
"unsigned-varint",
|
"unsigned-varint",
|
||||||
"void",
|
"void",
|
||||||
"wasm-timer",
|
"wasm-timer",
|
||||||
|
@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
- Raise MSRV to 1.65.
|
- Raise MSRV to 1.65.
|
||||||
See [PR 3715].
|
See [PR 3715].
|
||||||
|
- Remove deprecated items. See [PR 3862].
|
||||||
|
|
||||||
[PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715
|
[PR 3715]: https://github.com/libp2p/rust-libp2p/pull/3715
|
||||||
|
[PR 3862]: https://github.com/libp2p/rust-libp2p/pull/3862
|
||||||
|
|
||||||
## 0.44.4
|
## 0.44.4
|
||||||
|
|
||||||
|
@ -31,7 +31,6 @@ quick-protobuf-codec = { workspace = true }
|
|||||||
hex_fmt = "0.3.0"
|
hex_fmt = "0.3.0"
|
||||||
regex = "1.8.1"
|
regex = "1.8.1"
|
||||||
serde = { version = "1", optional = true, features = ["derive"] }
|
serde = { version = "1", optional = true, features = ["derive"] }
|
||||||
thiserror = "1.0"
|
|
||||||
wasm-timer = "0.2.5"
|
wasm-timer = "0.2.5"
|
||||||
instant = "0.1.11"
|
instant = "0.1.11"
|
||||||
void = "1.0.2"
|
void = "1.0.2"
|
||||||
|
@ -50,11 +50,11 @@ use crate::config::{Config, ValidationMode};
|
|||||||
use crate::gossip_promises::GossipPromises;
|
use crate::gossip_promises::GossipPromises;
|
||||||
use crate::handler::{Handler, HandlerEvent, HandlerIn};
|
use crate::handler::{Handler, HandlerEvent, HandlerIn};
|
||||||
use crate::mcache::MessageCache;
|
use crate::mcache::MessageCache;
|
||||||
use crate::metrics_priv::{Churn, Config as MetricsConfig, Inclusion, Metrics, Penalty};
|
use crate::metrics::{Churn, Config as MetricsConfig, Inclusion, Metrics, Penalty};
|
||||||
use crate::peer_score::{PeerScore, PeerScoreParams, PeerScoreThresholds, RejectReason};
|
use crate::peer_score::{PeerScore, PeerScoreParams, PeerScoreThresholds, RejectReason};
|
||||||
use crate::protocol_priv::{ProtocolConfig, SIGNING_PREFIX};
|
use crate::protocol::{ProtocolConfig, SIGNING_PREFIX};
|
||||||
use crate::subscription_filter_priv::{AllowAllSubscriptionFilter, TopicSubscriptionFilter};
|
use crate::subscription_filter::{AllowAllSubscriptionFilter, TopicSubscriptionFilter};
|
||||||
use crate::time_cache_priv::{DuplicateCache, TimeCache};
|
use crate::time_cache::{DuplicateCache, TimeCache};
|
||||||
use crate::topic::{Hasher, Topic, TopicHash};
|
use crate::topic::{Hasher, Topic, TopicHash};
|
||||||
use crate::transform::{DataTransform, IdentityTransform};
|
use crate::transform::{DataTransform, IdentityTransform};
|
||||||
use crate::types::{
|
use crate::types::{
|
||||||
@ -3824,7 +3824,7 @@ mod local_test {
|
|||||||
let mut length_codec = unsigned_varint::codec::UviBytes::default();
|
let mut length_codec = unsigned_varint::codec::UviBytes::default();
|
||||||
length_codec.set_max_len(max_transmit_size);
|
length_codec.set_max_len(max_transmit_size);
|
||||||
let mut codec =
|
let mut codec =
|
||||||
crate::protocol_priv::GossipsubCodec::new(length_codec, ValidationMode::Permissive);
|
crate::protocol::GossipsubCodec::new(length_codec, ValidationMode::Permissive);
|
||||||
|
|
||||||
let rpc_proto = rpc.into_protobuf();
|
let rpc_proto = rpc.into_protobuf();
|
||||||
let fragmented_messages = gs
|
let fragmented_messages = gs
|
||||||
|
@ -21,7 +21,7 @@
|
|||||||
// Collection of tests for the gossipsub network behaviour
|
// Collection of tests for the gossipsub network behaviour
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::subscription_filter_priv::WhitelistSubscriptionFilter;
|
use crate::subscription_filter::WhitelistSubscriptionFilter;
|
||||||
use crate::transform::{DataTransform, IdentityTransform};
|
use crate::transform::{DataTransform, IdentityTransform};
|
||||||
use crate::types::FastMessageId;
|
use crate::types::FastMessageId;
|
||||||
use crate::ValidationError;
|
use crate::ValidationError;
|
||||||
|
@ -884,7 +884,7 @@ impl std::fmt::Debug for Config {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::protocol_priv::ProtocolConfig;
|
use crate::protocol::ProtocolConfig;
|
||||||
use crate::topic::IdentityHash;
|
use crate::topic::IdentityHash;
|
||||||
use crate::types::PeerKind;
|
use crate::types::PeerKind;
|
||||||
use crate::Topic;
|
use crate::Topic;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Copyright 2023 Protocol Labs.
|
// Copyright 2020 Sigma Prime Pty Ltd.
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
// copy of this software and associated documentation files (the "Software"),
|
// copy of this software and associated documentation files (the "Software"),
|
||||||
@ -18,26 +18,105 @@
|
|||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
// DEALINGS IN THE SOFTWARE.
|
// DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
#[deprecated(
|
//! Error types that can result from gossipsub.
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use `libp2p::gossipsub::PublishError` instead, as the `error` module will become crate-private in the future."
|
|
||||||
)]
|
|
||||||
pub type PublishError = crate::error_priv::PublishError;
|
|
||||||
|
|
||||||
#[deprecated(
|
use libp2p_core::identity::error::SigningError;
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use `libp2p::gossipsub::SubscriptionError` instead, as the `error` module will become crate-private in the future."
|
|
||||||
)]
|
|
||||||
pub type SubscriptionError = crate::error_priv::SubscriptionError;
|
|
||||||
|
|
||||||
#[deprecated(note = "This error will no longer be emitted")]
|
/// Error associated with publishing a gossipsub message.
|
||||||
pub type GossipsubHandlerError = crate::error_priv::HandlerError;
|
#[derive(Debug)]
|
||||||
|
pub enum PublishError {
|
||||||
|
/// This message has already been published.
|
||||||
|
Duplicate,
|
||||||
|
/// An error occurred whilst signing the message.
|
||||||
|
SigningError(SigningError),
|
||||||
|
/// There were no peers to send this message to.
|
||||||
|
InsufficientPeers,
|
||||||
|
/// The overall message was too large. This could be due to excessive topics or an excessive
|
||||||
|
/// message size.
|
||||||
|
MessageTooLarge,
|
||||||
|
/// The compression algorithm failed.
|
||||||
|
TransformFailed(std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
#[deprecated(note = "This error will no longer be emitted")]
|
impl std::fmt::Display for PublishError {
|
||||||
pub type HandlerError = crate::error_priv::HandlerError;
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
write!(f, "{self:?}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[deprecated(
|
impl std::error::Error for PublishError {
|
||||||
since = "0.44.0",
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
note = "Use `libp2p::gossipsub::ValidationError` instead, as the `error` module will become crate-private in the future."
|
match self {
|
||||||
)]
|
Self::SigningError(err) => Some(err),
|
||||||
pub type ValidationError = crate::error_priv::ValidationError;
|
Self::TransformFailed(err) => Some(err),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Error associated with subscribing to a topic.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum SubscriptionError {
|
||||||
|
/// Couldn't publish our subscription
|
||||||
|
PublishError(PublishError),
|
||||||
|
/// We are not allowed to subscribe to this topic by the subscription filter
|
||||||
|
NotAllowed,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for SubscriptionError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
write!(f, "{self:?}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for SubscriptionError {
|
||||||
|
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::PublishError(err) => Some(err),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<SigningError> for PublishError {
|
||||||
|
fn from(error: SigningError) -> Self {
|
||||||
|
PublishError::SigningError(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum ValidationError {
|
||||||
|
/// The message has an invalid signature,
|
||||||
|
InvalidSignature,
|
||||||
|
/// The sequence number was empty, expected a value.
|
||||||
|
EmptySequenceNumber,
|
||||||
|
/// The sequence number was the incorrect size
|
||||||
|
InvalidSequenceNumber,
|
||||||
|
/// The PeerId was invalid
|
||||||
|
InvalidPeerId,
|
||||||
|
/// Signature existed when validation has been sent to
|
||||||
|
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
||||||
|
SignaturePresent,
|
||||||
|
/// Sequence number existed when validation has been sent to
|
||||||
|
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
||||||
|
SequenceNumberPresent,
|
||||||
|
/// Message source existed when validation has been sent to
|
||||||
|
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
||||||
|
MessageSourcePresent,
|
||||||
|
/// The data transformation failed.
|
||||||
|
TransformFailed,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ValidationError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
write!(f, "{self:?}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ValidationError {}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for PublishError {
|
||||||
|
fn from(error: std::io::Error) -> PublishError {
|
||||||
|
PublishError::TransformFailed(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,141 +0,0 @@
|
|||||||
// Copyright 2020 Sigma Prime Pty Ltd.
|
|
||||||
//
|
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
|
||||||
// copy of this software and associated documentation files (the "Software"),
|
|
||||||
// to deal in the Software without restriction, including without limitation
|
|
||||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
// and/or sell copies of the Software, and to permit persons to whom the
|
|
||||||
// Software is furnished to do so, subject to the following conditions:
|
|
||||||
//
|
|
||||||
// The above copyright notice and this permission notice shall be included in
|
|
||||||
// all copies or substantial portions of the Software.
|
|
||||||
//
|
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
||||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
||||||
// DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
//! Error types that can result from gossipsub.
|
|
||||||
|
|
||||||
use libp2p_core::identity::error::SigningError;
|
|
||||||
use libp2p_core::upgrade::ProtocolError;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
/// Error associated with publishing a gossipsub message.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum PublishError {
|
|
||||||
/// This message has already been published.
|
|
||||||
Duplicate,
|
|
||||||
/// An error occurred whilst signing the message.
|
|
||||||
SigningError(SigningError),
|
|
||||||
/// There were no peers to send this message to.
|
|
||||||
InsufficientPeers,
|
|
||||||
/// The overall message was too large. This could be due to excessive topics or an excessive
|
|
||||||
/// message size.
|
|
||||||
MessageTooLarge,
|
|
||||||
/// The compression algorithm failed.
|
|
||||||
TransformFailed(std::io::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for PublishError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
write!(f, "{self:?}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for PublishError {
|
|
||||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
||||||
match self {
|
|
||||||
Self::SigningError(err) => Some(err),
|
|
||||||
Self::TransformFailed(err) => Some(err),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Error associated with subscribing to a topic.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum SubscriptionError {
|
|
||||||
/// Couldn't publish our subscription
|
|
||||||
PublishError(PublishError),
|
|
||||||
/// We are not allowed to subscribe to this topic by the subscription filter
|
|
||||||
NotAllowed,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for SubscriptionError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
write!(f, "{self:?}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for SubscriptionError {
|
|
||||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
|
||||||
match self {
|
|
||||||
Self::PublishError(err) => Some(err),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<SigningError> for PublishError {
|
|
||||||
fn from(error: SigningError) -> Self {
|
|
||||||
PublishError::SigningError(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Errors that can occur in the protocols handler.
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum HandlerError {
|
|
||||||
#[error("The maximum number of inbound substreams created has been exceeded.")]
|
|
||||||
MaxInboundSubstreams,
|
|
||||||
#[error("The maximum number of outbound substreams created has been exceeded.")]
|
|
||||||
MaxOutboundSubstreams,
|
|
||||||
#[error("The message exceeds the maximum transmission size.")]
|
|
||||||
MaxTransmissionSize,
|
|
||||||
#[error("Protocol negotiation timeout.")]
|
|
||||||
NegotiationTimeout,
|
|
||||||
#[error("Protocol negotiation failed.")]
|
|
||||||
NegotiationProtocolError(ProtocolError),
|
|
||||||
#[error("Failed to encode or decode")]
|
|
||||||
Codec(#[from] quick_protobuf_codec::Error),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub enum ValidationError {
|
|
||||||
/// The message has an invalid signature,
|
|
||||||
InvalidSignature,
|
|
||||||
/// The sequence number was empty, expected a value.
|
|
||||||
EmptySequenceNumber,
|
|
||||||
/// The sequence number was the incorrect size
|
|
||||||
InvalidSequenceNumber,
|
|
||||||
/// The PeerId was invalid
|
|
||||||
InvalidPeerId,
|
|
||||||
/// Signature existed when validation has been sent to
|
|
||||||
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
|
||||||
SignaturePresent,
|
|
||||||
/// Sequence number existed when validation has been sent to
|
|
||||||
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
|
||||||
SequenceNumberPresent,
|
|
||||||
/// Message source existed when validation has been sent to
|
|
||||||
/// [`crate::behaviour::MessageAuthenticity::Anonymous`].
|
|
||||||
MessageSourcePresent,
|
|
||||||
/// The data transformation failed.
|
|
||||||
TransformFailed,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for ValidationError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
write!(f, "{self:?}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for ValidationError {}
|
|
||||||
|
|
||||||
impl From<std::io::Error> for PublishError {
|
|
||||||
fn from(error: std::io::Error) -> PublishError {
|
|
||||||
PublishError::TransformFailed(error)
|
|
||||||
}
|
|
||||||
}
|
|
@ -18,7 +18,7 @@
|
|||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
// DEALINGS IN THE SOFTWARE.
|
// DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
use crate::protocol_priv::{GossipsubCodec, ProtocolConfig};
|
use crate::protocol::{GossipsubCodec, ProtocolConfig};
|
||||||
use crate::rpc_proto::proto;
|
use crate::rpc_proto::proto;
|
||||||
use crate::types::{PeerKind, RawMessage, Rpc};
|
use crate::types::{PeerKind, RawMessage, Rpc};
|
||||||
use crate::ValidationError;
|
use crate::ValidationError;
|
||||||
|
@ -138,70 +138,32 @@
|
|||||||
|
|
||||||
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
|
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
|
||||||
|
|
||||||
pub mod error;
|
|
||||||
|
|
||||||
mod metrics_priv;
|
|
||||||
#[deprecated(
|
|
||||||
note = "The `metrics` module will be made private in the future and should not be depended on."
|
|
||||||
)]
|
|
||||||
pub mod metrics {
|
|
||||||
pub use super::metrics_priv::*;
|
|
||||||
}
|
|
||||||
|
|
||||||
mod protocol_priv;
|
|
||||||
#[deprecated(
|
|
||||||
note = "The `protocol` module will be made private in the future and should not be depended on."
|
|
||||||
)]
|
|
||||||
pub mod protocol {
|
|
||||||
pub use super::protocol_priv::*;
|
|
||||||
}
|
|
||||||
|
|
||||||
mod subscription_filter_priv;
|
|
||||||
#[deprecated(
|
|
||||||
note = "The `subscription_filter` module will be made private in the future, import the types from the crate root instead."
|
|
||||||
)]
|
|
||||||
pub mod subscription_filter {
|
|
||||||
pub use super::subscription_filter_priv::*;
|
|
||||||
|
|
||||||
pub mod regex {
|
|
||||||
pub use crate::subscription_filter_priv::RegexSubscriptionFilter;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mod time_cache_priv;
|
|
||||||
#[deprecated(
|
|
||||||
note = "The `time_cache` module will be made private in the future and should not be depended on."
|
|
||||||
)]
|
|
||||||
pub mod time_cache {
|
|
||||||
pub use super::time_cache_priv::*;
|
|
||||||
}
|
|
||||||
|
|
||||||
mod backoff;
|
mod backoff;
|
||||||
mod behaviour;
|
mod behaviour;
|
||||||
mod config;
|
mod config;
|
||||||
mod error_priv;
|
mod error;
|
||||||
mod gossip_promises;
|
mod gossip_promises;
|
||||||
mod handler;
|
mod handler;
|
||||||
mod mcache;
|
mod mcache;
|
||||||
|
mod metrics;
|
||||||
mod peer_score;
|
mod peer_score;
|
||||||
|
mod protocol;
|
||||||
|
mod rpc_proto;
|
||||||
|
mod subscription_filter;
|
||||||
|
mod time_cache;
|
||||||
mod topic;
|
mod topic;
|
||||||
mod transform;
|
mod transform;
|
||||||
mod types;
|
mod types;
|
||||||
|
|
||||||
mod rpc_proto;
|
|
||||||
|
|
||||||
#[deprecated(note = "This error will no longer be emitted")]
|
|
||||||
pub type HandlerError = error_priv::HandlerError;
|
|
||||||
|
|
||||||
pub use self::behaviour::{Behaviour, Event, MessageAuthenticity};
|
pub use self::behaviour::{Behaviour, Event, MessageAuthenticity};
|
||||||
pub use self::config::{Config, ConfigBuilder, ValidationMode, Version};
|
pub use self::config::{Config, ConfigBuilder, ValidationMode, Version};
|
||||||
pub use self::error_priv::{PublishError, SubscriptionError, ValidationError};
|
pub use self::error::{PublishError, SubscriptionError, ValidationError};
|
||||||
pub use self::metrics_priv::Config as MetricsConfig;
|
pub use self::metrics::Config as MetricsConfig;
|
||||||
pub use self::peer_score::{
|
pub use self::peer_score::{
|
||||||
score_parameter_decay, score_parameter_decay_with_base, PeerScoreParams, PeerScoreThresholds,
|
score_parameter_decay, score_parameter_decay_with_base, PeerScoreParams, PeerScoreThresholds,
|
||||||
TopicScoreParams,
|
TopicScoreParams,
|
||||||
};
|
};
|
||||||
pub use self::subscription_filter_priv::{
|
pub use self::subscription_filter::{
|
||||||
AllowAllSubscriptionFilter, CallbackSubscriptionFilter, CombinedSubscriptionFilters,
|
AllowAllSubscriptionFilter, CallbackSubscriptionFilter, CombinedSubscriptionFilters,
|
||||||
MaxCountSubscriptionFilter, RegexSubscriptionFilter, TopicSubscriptionFilter,
|
MaxCountSubscriptionFilter, RegexSubscriptionFilter, TopicSubscriptionFilter,
|
||||||
WhitelistSubscriptionFilter,
|
WhitelistSubscriptionFilter,
|
||||||
@ -210,53 +172,5 @@ pub use self::topic::{Hasher, Topic, TopicHash};
|
|||||||
pub use self::transform::{DataTransform, IdentityTransform};
|
pub use self::transform::{DataTransform, IdentityTransform};
|
||||||
pub use self::types::{FastMessageId, Message, MessageAcceptance, MessageId, RawMessage, Rpc};
|
pub use self::types::{FastMessageId, Message, MessageAcceptance, MessageId, RawMessage, Rpc};
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use `Behaviour` instead of `Gossipsub` for Network Behaviour, i.e. `libp2p::gossipsub::Behaviour"
|
|
||||||
)]
|
|
||||||
pub type Gossipsub = Behaviour;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::Event"
|
|
||||||
)]
|
|
||||||
pub type GossipsubEvent = Event;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::Config"
|
|
||||||
)]
|
|
||||||
pub type GossipsubConfig = Config;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::Message"
|
|
||||||
)]
|
|
||||||
pub type GossipsubMessage = Message;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::Rpc"
|
|
||||||
)]
|
|
||||||
pub type GossipsubRpc = Rpc;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` infix, i.e. `libp2p::gossipsub::RawMessage"
|
|
||||||
)]
|
|
||||||
pub type RawGossipsubMessage = RawMessage;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::ConfigBuilder"
|
|
||||||
)]
|
|
||||||
pub type GossipsubConfigBuilder = ConfigBuilder;
|
|
||||||
|
|
||||||
#[deprecated(
|
|
||||||
since = "0.44.0",
|
|
||||||
note = "Use re-exports that omit `Gossipsub` prefix, i.e. `libp2p::gossipsub::Version"
|
|
||||||
)]
|
|
||||||
pub type GossipsubVersion = Version;
|
|
||||||
|
|
||||||
pub type IdentTopic = Topic<self::topic::IdentityHash>;
|
pub type IdentTopic = Topic<self::topic::IdentityHash>;
|
||||||
pub type Sha256Topic = Topic<self::topic::Sha256Hash>;
|
pub type Sha256Topic = Topic<self::topic::Sha256Hash>;
|
||||||
|
@ -99,7 +99,7 @@ impl Default for Config {
|
|||||||
type EverSubscribed = bool;
|
type EverSubscribed = bool;
|
||||||
|
|
||||||
/// A collection of metrics used throughout the Gossipsub behaviour.
|
/// A collection of metrics used throughout the Gossipsub behaviour.
|
||||||
pub struct Metrics {
|
pub(crate) struct Metrics {
|
||||||
/* Configuration parameters */
|
/* Configuration parameters */
|
||||||
/// Maximum number of topics for which we store metrics. This helps keep the metrics bounded.
|
/// Maximum number of topics for which we store metrics. This helps keep the metrics bounded.
|
||||||
max_topics: usize,
|
max_topics: usize,
|
||||||
@ -177,7 +177,7 @@ pub struct Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Metrics {
|
impl Metrics {
|
||||||
pub fn new(registry: &mut Registry, config: Config) -> Self {
|
pub(crate) fn new(registry: &mut Registry, config: Config) -> Self {
|
||||||
// Destructure the config to be sure everything is used.
|
// Destructure the config to be sure everything is used.
|
||||||
let Config {
|
let Config {
|
||||||
max_topics,
|
max_topics,
|
||||||
@ -356,7 +356,7 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register how many peers do we known are subscribed to this topic.
|
/// Register how many peers do we known are subscribed to this topic.
|
||||||
pub fn set_topic_peers(&mut self, topic: &TopicHash, count: usize) {
|
pub(crate) fn set_topic_peers(&mut self, topic: &TopicHash, count: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_peers_count
|
self.topic_peers_count
|
||||||
.get_or_create(topic)
|
.get_or_create(topic)
|
||||||
@ -368,7 +368,7 @@ impl Metrics {
|
|||||||
|
|
||||||
/// Registers the subscription to a topic if the configured limits allow it.
|
/// Registers the subscription to a topic if the configured limits allow it.
|
||||||
/// Sets the registered number of peers in the mesh to 0.
|
/// Sets the registered number of peers in the mesh to 0.
|
||||||
pub fn joined(&mut self, topic: &TopicHash) {
|
pub(crate) fn joined(&mut self, topic: &TopicHash) {
|
||||||
if self.topic_info.contains_key(topic) || self.topic_info.len() < self.max_topics {
|
if self.topic_info.contains_key(topic) || self.topic_info.len() < self.max_topics {
|
||||||
self.topic_info.insert(topic.clone(), true);
|
self.topic_info.insert(topic.clone(), true);
|
||||||
let was_subscribed = self.topic_subscription_status.get_or_create(topic).set(1);
|
let was_subscribed = self.topic_subscription_status.get_or_create(topic).set(1);
|
||||||
@ -379,7 +379,7 @@ impl Metrics {
|
|||||||
|
|
||||||
/// Registers the unsubscription to a topic if the topic was previously allowed.
|
/// Registers the unsubscription to a topic if the topic was previously allowed.
|
||||||
/// Sets the registered number of peers in the mesh to 0.
|
/// Sets the registered number of peers in the mesh to 0.
|
||||||
pub fn left(&mut self, topic: &TopicHash) {
|
pub(crate) fn left(&mut self, topic: &TopicHash) {
|
||||||
if self.topic_info.contains_key(topic) {
|
if self.topic_info.contains_key(topic) {
|
||||||
// Depending on the configured topic bounds we could miss a mesh topic.
|
// Depending on the configured topic bounds we could miss a mesh topic.
|
||||||
// So, check first if the topic was previously allowed.
|
// So, check first if the topic was previously allowed.
|
||||||
@ -390,7 +390,7 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register the inclusion of peers in our mesh due to some reason.
|
/// Register the inclusion of peers in our mesh due to some reason.
|
||||||
pub fn peers_included(&mut self, topic: &TopicHash, reason: Inclusion, count: usize) {
|
pub(crate) fn peers_included(&mut self, topic: &TopicHash, reason: Inclusion, count: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.mesh_peer_inclusion_events
|
self.mesh_peer_inclusion_events
|
||||||
.get_or_create(&InclusionLabel {
|
.get_or_create(&InclusionLabel {
|
||||||
@ -402,7 +402,7 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register the removal of peers in our mesh due to some reason.
|
/// Register the removal of peers in our mesh due to some reason.
|
||||||
pub fn peers_removed(&mut self, topic: &TopicHash, reason: Churn, count: usize) {
|
pub(crate) fn peers_removed(&mut self, topic: &TopicHash, reason: Churn, count: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.mesh_peer_churn_events
|
self.mesh_peer_churn_events
|
||||||
.get_or_create(&ChurnLabel {
|
.get_or_create(&ChurnLabel {
|
||||||
@ -414,7 +414,7 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register the current number of peers in our mesh for this topic.
|
/// Register the current number of peers in our mesh for this topic.
|
||||||
pub fn set_mesh_peers(&mut self, topic: &TopicHash, count: usize) {
|
pub(crate) fn set_mesh_peers(&mut self, topic: &TopicHash, count: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
// Due to limits, this topic could have not been allowed, so we check.
|
// Due to limits, this topic could have not been allowed, so we check.
|
||||||
self.mesh_peer_counts.get_or_create(topic).set(count as i64);
|
self.mesh_peer_counts.get_or_create(topic).set(count as i64);
|
||||||
@ -422,28 +422,28 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register that an invalid message was received on a specific topic.
|
/// Register that an invalid message was received on a specific topic.
|
||||||
pub fn register_invalid_message(&mut self, topic: &TopicHash) {
|
pub(crate) fn register_invalid_message(&mut self, topic: &TopicHash) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.invalid_messages.get_or_create(topic).inc();
|
self.invalid_messages.get_or_create(topic).inc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register a score penalty.
|
/// Register a score penalty.
|
||||||
pub fn register_score_penalty(&mut self, penalty: Penalty) {
|
pub(crate) fn register_score_penalty(&mut self, penalty: Penalty) {
|
||||||
self.scoring_penalties
|
self.scoring_penalties
|
||||||
.get_or_create(&PenaltyLabel { penalty })
|
.get_or_create(&PenaltyLabel { penalty })
|
||||||
.inc();
|
.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registers that a message was published on a specific topic.
|
/// Registers that a message was published on a specific topic.
|
||||||
pub fn register_published_message(&mut self, topic: &TopicHash) {
|
pub(crate) fn register_published_message(&mut self, topic: &TopicHash) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_msg_published.get_or_create(topic).inc();
|
self.topic_msg_published.get_or_create(topic).inc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register sending a message over a topic.
|
/// Register sending a message over a topic.
|
||||||
pub fn msg_sent(&mut self, topic: &TopicHash, bytes: usize) {
|
pub(crate) fn msg_sent(&mut self, topic: &TopicHash, bytes: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_msg_sent_counts.get_or_create(topic).inc();
|
self.topic_msg_sent_counts.get_or_create(topic).inc();
|
||||||
self.topic_msg_sent_bytes
|
self.topic_msg_sent_bytes
|
||||||
@ -453,14 +453,14 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register that a message was received (and was not a duplicate).
|
/// Register that a message was received (and was not a duplicate).
|
||||||
pub fn msg_recvd(&mut self, topic: &TopicHash) {
|
pub(crate) fn msg_recvd(&mut self, topic: &TopicHash) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_msg_recv_counts.get_or_create(topic).inc();
|
self.topic_msg_recv_counts.get_or_create(topic).inc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register that a message was received (could have been a duplicate).
|
/// Register that a message was received (could have been a duplicate).
|
||||||
pub fn msg_recvd_unfiltered(&mut self, topic: &TopicHash, bytes: usize) {
|
pub(crate) fn msg_recvd_unfiltered(&mut self, topic: &TopicHash, bytes: usize) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_msg_recv_counts_unfiltered
|
self.topic_msg_recv_counts_unfiltered
|
||||||
.get_or_create(topic)
|
.get_or_create(topic)
|
||||||
@ -471,7 +471,11 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn register_msg_validation(&mut self, topic: &TopicHash, validation: &MessageAcceptance) {
|
pub(crate) fn register_msg_validation(
|
||||||
|
&mut self,
|
||||||
|
topic: &TopicHash,
|
||||||
|
validation: &MessageAcceptance,
|
||||||
|
) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
match validation {
|
match validation {
|
||||||
MessageAcceptance::Accept => self.accepted_messages.get_or_create(topic).inc(),
|
MessageAcceptance::Accept => self.accepted_messages.get_or_create(topic).inc(),
|
||||||
@ -482,38 +486,38 @@ impl Metrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Register a memcache miss.
|
/// Register a memcache miss.
|
||||||
pub fn memcache_miss(&mut self) {
|
pub(crate) fn memcache_miss(&mut self) {
|
||||||
self.memcache_misses.inc();
|
self.memcache_misses.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register sending an IWANT msg for this topic.
|
/// Register sending an IWANT msg for this topic.
|
||||||
pub fn register_iwant(&mut self, topic: &TopicHash) {
|
pub(crate) fn register_iwant(&mut self, topic: &TopicHash) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.topic_iwant_msgs.get_or_create(topic).inc();
|
self.topic_iwant_msgs.get_or_create(topic).inc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Observes a heartbeat duration.
|
/// Observes a heartbeat duration.
|
||||||
pub fn observe_heartbeat_duration(&mut self, millis: u64) {
|
pub(crate) fn observe_heartbeat_duration(&mut self, millis: u64) {
|
||||||
self.heartbeat_duration.observe(millis as f64);
|
self.heartbeat_duration.observe(millis as f64);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Observe a score of a mesh peer.
|
/// Observe a score of a mesh peer.
|
||||||
pub fn observe_mesh_peers_score(&mut self, topic: &TopicHash, score: f64) {
|
pub(crate) fn observe_mesh_peers_score(&mut self, topic: &TopicHash, score: f64) {
|
||||||
if self.register_topic(topic).is_ok() {
|
if self.register_topic(topic).is_ok() {
|
||||||
self.score_per_mesh.get_or_create(topic).observe(score);
|
self.score_per_mesh.get_or_create(topic).observe(score);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register a new peers connection based on its protocol.
|
/// Register a new peers connection based on its protocol.
|
||||||
pub fn peer_protocol_connected(&mut self, kind: PeerKind) {
|
pub(crate) fn peer_protocol_connected(&mut self, kind: PeerKind) {
|
||||||
self.peers_per_protocol
|
self.peers_per_protocol
|
||||||
.get_or_create(&ProtocolLabel { protocol: kind })
|
.get_or_create(&ProtocolLabel { protocol: kind })
|
||||||
.inc();
|
.inc();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a peer from the counter based on its protocol when it disconnects.
|
/// Removes a peer from the counter based on its protocol when it disconnects.
|
||||||
pub fn peer_protocol_disconnected(&mut self, kind: PeerKind) {
|
pub(crate) fn peer_protocol_disconnected(&mut self, kind: PeerKind) {
|
||||||
let metric = self
|
let metric = self
|
||||||
.peers_per_protocol
|
.peers_per_protocol
|
||||||
.get_or_create(&ProtocolLabel { protocol: kind });
|
.get_or_create(&ProtocolLabel { protocol: kind });
|
||||||
@ -526,7 +530,7 @@ impl Metrics {
|
|||||||
|
|
||||||
/// Reasons why a peer was included in the mesh.
|
/// Reasons why a peer was included in the mesh.
|
||||||
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
||||||
pub enum Inclusion {
|
pub(crate) enum Inclusion {
|
||||||
/// Peer was a fanaout peer.
|
/// Peer was a fanaout peer.
|
||||||
Fanout,
|
Fanout,
|
||||||
/// Included from random selection.
|
/// Included from random selection.
|
||||||
@ -539,7 +543,7 @@ pub enum Inclusion {
|
|||||||
|
|
||||||
/// Reasons why a peer was removed from the mesh.
|
/// Reasons why a peer was removed from the mesh.
|
||||||
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
||||||
pub enum Churn {
|
pub(crate) enum Churn {
|
||||||
/// Peer disconnected.
|
/// Peer disconnected.
|
||||||
Dc,
|
Dc,
|
||||||
/// Peer had a bad score.
|
/// Peer had a bad score.
|
||||||
@ -554,7 +558,7 @@ pub enum Churn {
|
|||||||
|
|
||||||
/// Kinds of reasons a peer's score has been penalized
|
/// Kinds of reasons a peer's score has been penalized
|
||||||
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
#[derive(PartialEq, Eq, Hash, EncodeLabelValue, Clone, Debug)]
|
||||||
pub enum Penalty {
|
pub(crate) enum Penalty {
|
||||||
/// A peer grafted before waiting the back-off time.
|
/// A peer grafted before waiting the back-off time.
|
||||||
GraftBackoff,
|
GraftBackoff,
|
||||||
/// A Peer did not respond to an IWANT request in time.
|
/// A Peer did not respond to an IWANT request in time.
|
@ -21,8 +21,8 @@
|
|||||||
//!
|
//!
|
||||||
//! Manages and stores the Scoring logic of a particular peer on the gossipsub behaviour.
|
//! Manages and stores the Scoring logic of a particular peer on the gossipsub behaviour.
|
||||||
|
|
||||||
use crate::metrics_priv::{Metrics, Penalty};
|
use crate::metrics::{Metrics, Penalty};
|
||||||
use crate::time_cache_priv::TimeCache;
|
use crate::time_cache::TimeCache;
|
||||||
use crate::{MessageId, TopicHash};
|
use crate::{MessageId, TopicHash};
|
||||||
use libp2p_identity::PeerId;
|
use libp2p_identity::PeerId;
|
||||||
use log::{debug, trace, warn};
|
use log::{debug, trace, warn};
|
||||||
|
@ -36,7 +36,7 @@ struct ExpiringElement<Element> {
|
|||||||
expires: Instant,
|
expires: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct TimeCache<Key, Value> {
|
pub(crate) struct TimeCache<Key, Value> {
|
||||||
/// Mapping a key to its value together with its latest expire time (can be updated through
|
/// Mapping a key to its value together with its latest expire time (can be updated through
|
||||||
/// reinserts).
|
/// reinserts).
|
||||||
map: FnvHashMap<Key, ExpiringElement<Value>>,
|
map: FnvHashMap<Key, ExpiringElement<Value>>,
|
||||||
@ -46,42 +46,20 @@ pub struct TimeCache<Key, Value> {
|
|||||||
ttl: Duration,
|
ttl: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct OccupiedEntry<'a, K, V> {
|
pub(crate) struct OccupiedEntry<'a, K, V> {
|
||||||
expiration: Instant,
|
|
||||||
entry: hash_map::OccupiedEntry<'a, K, ExpiringElement<V>>,
|
entry: hash_map::OccupiedEntry<'a, K, ExpiringElement<V>>,
|
||||||
list: &'a mut VecDeque<ExpiringElement<K>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, K, V> OccupiedEntry<'a, K, V>
|
impl<'a, K, V> OccupiedEntry<'a, K, V>
|
||||||
where
|
where
|
||||||
K: Eq + std::hash::Hash + Clone,
|
K: Eq + std::hash::Hash + Clone,
|
||||||
{
|
{
|
||||||
pub fn into_mut(self) -> &'a mut V {
|
pub(crate) fn into_mut(self) -> &'a mut V {
|
||||||
&mut self.entry.into_mut().element
|
&mut self.entry.into_mut().element
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert_without_updating_expiration(&mut self, value: V) -> V {
|
|
||||||
//keep old expiration, only replace value of element
|
|
||||||
::std::mem::replace(&mut self.entry.get_mut().element, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn insert_and_update_expiration(&mut self, value: V) -> V {
|
|
||||||
//We push back an additional element, the first reference in the list will be ignored
|
|
||||||
// since we also updated the expires in the map, see below.
|
|
||||||
self.list.push_back(ExpiringElement {
|
|
||||||
element: self.entry.key().clone(),
|
|
||||||
expires: self.expiration,
|
|
||||||
});
|
|
||||||
self.entry
|
|
||||||
.insert(ExpiringElement {
|
|
||||||
element: value,
|
|
||||||
expires: self.expiration,
|
|
||||||
})
|
|
||||||
.element
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct VacantEntry<'a, K, V> {
|
pub(crate) struct VacantEntry<'a, K, V> {
|
||||||
expiration: Instant,
|
expiration: Instant,
|
||||||
entry: hash_map::VacantEntry<'a, K, ExpiringElement<V>>,
|
entry: hash_map::VacantEntry<'a, K, ExpiringElement<V>>,
|
||||||
list: &'a mut VecDeque<ExpiringElement<K>>,
|
list: &'a mut VecDeque<ExpiringElement<K>>,
|
||||||
@ -91,7 +69,7 @@ impl<'a, K, V> VacantEntry<'a, K, V>
|
|||||||
where
|
where
|
||||||
K: Eq + std::hash::Hash + Clone,
|
K: Eq + std::hash::Hash + Clone,
|
||||||
{
|
{
|
||||||
pub fn insert(self, value: V) -> &'a mut V {
|
pub(crate) fn insert(self, value: V) -> &'a mut V {
|
||||||
self.list.push_back(ExpiringElement {
|
self.list.push_back(ExpiringElement {
|
||||||
element: self.entry.key().clone(),
|
element: self.entry.key().clone(),
|
||||||
expires: self.expiration,
|
expires: self.expiration,
|
||||||
@ -106,7 +84,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Entry<'a, K: 'a, V: 'a> {
|
pub(crate) enum Entry<'a, K: 'a, V: 'a> {
|
||||||
Occupied(OccupiedEntry<'a, K, V>),
|
Occupied(OccupiedEntry<'a, K, V>),
|
||||||
Vacant(VacantEntry<'a, K, V>),
|
Vacant(VacantEntry<'a, K, V>),
|
||||||
}
|
}
|
||||||
@ -115,7 +93,7 @@ impl<'a, K: 'a, V: 'a> Entry<'a, K, V>
|
|||||||
where
|
where
|
||||||
K: Eq + std::hash::Hash + Clone,
|
K: Eq + std::hash::Hash + Clone,
|
||||||
{
|
{
|
||||||
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
|
pub(crate) fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
|
||||||
match self {
|
match self {
|
||||||
Entry::Occupied(entry) => entry.into_mut(),
|
Entry::Occupied(entry) => entry.into_mut(),
|
||||||
Entry::Vacant(entry) => entry.insert(default()),
|
Entry::Vacant(entry) => entry.insert(default()),
|
||||||
@ -127,7 +105,7 @@ impl<Key, Value> TimeCache<Key, Value>
|
|||||||
where
|
where
|
||||||
Key: Eq + std::hash::Hash + Clone,
|
Key: Eq + std::hash::Hash + Clone,
|
||||||
{
|
{
|
||||||
pub fn new(ttl: Duration) -> Self {
|
pub(crate) fn new(ttl: Duration) -> Self {
|
||||||
TimeCache {
|
TimeCache {
|
||||||
map: FnvHashMap::default(),
|
map: FnvHashMap::default(),
|
||||||
list: VecDeque::new(),
|
list: VecDeque::new(),
|
||||||
@ -149,15 +127,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn entry(&mut self, key: Key) -> Entry<Key, Value> {
|
pub(crate) fn entry(&mut self, key: Key) -> Entry<Key, Value> {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
self.remove_expired_keys(now);
|
self.remove_expired_keys(now);
|
||||||
match self.map.entry(key) {
|
match self.map.entry(key) {
|
||||||
Occupied(entry) => Entry::Occupied(OccupiedEntry {
|
Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
|
||||||
expiration: now + self.ttl,
|
|
||||||
entry,
|
|
||||||
list: &mut self.list,
|
|
||||||
}),
|
|
||||||
Vacant(entry) => Entry::Vacant(VacantEntry {
|
Vacant(entry) => Entry::Vacant(VacantEntry {
|
||||||
expiration: now + self.ttl,
|
expiration: now + self.ttl,
|
||||||
entry,
|
entry,
|
||||||
@ -167,31 +141,28 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Empties the entire cache.
|
/// Empties the entire cache.
|
||||||
pub fn clear(&mut self) {
|
#[cfg(test)]
|
||||||
|
pub(crate) fn clear(&mut self) {
|
||||||
self.map.clear();
|
self.map.clear();
|
||||||
self.list.clear();
|
self.list.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn contains_key(&self, key: &Key) -> bool {
|
pub(crate) fn contains_key(&self, key: &Key) -> bool {
|
||||||
self.map.contains_key(key)
|
self.map.contains_key(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, key: &Key) -> Option<&Value> {
|
pub(crate) fn get(&self, key: &Key) -> Option<&Value> {
|
||||||
self.map.get(key).map(|e| &e.element)
|
self.map.get(key).map(|e| &e.element)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mut(&mut self, key: &Key) -> Option<&mut Value> {
|
|
||||||
self.map.get_mut(key).map(|e| &mut e.element)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct DuplicateCache<Key>(TimeCache<Key, ()>);
|
pub(crate) struct DuplicateCache<Key>(TimeCache<Key, ()>);
|
||||||
|
|
||||||
impl<Key> DuplicateCache<Key>
|
impl<Key> DuplicateCache<Key>
|
||||||
where
|
where
|
||||||
Key: Eq + std::hash::Hash + Clone,
|
Key: Eq + std::hash::Hash + Clone,
|
||||||
{
|
{
|
||||||
pub fn new(ttl: Duration) -> Self {
|
pub(crate) fn new(ttl: Duration) -> Self {
|
||||||
Self(TimeCache::new(ttl))
|
Self(TimeCache::new(ttl))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,7 +170,7 @@ where
|
|||||||
//
|
//
|
||||||
// If the key was not present this returns `true`. If the value was already present this
|
// If the key was not present this returns `true`. If the value was already present this
|
||||||
// returns `false`.
|
// returns `false`.
|
||||||
pub fn insert(&mut self, key: Key) -> bool {
|
pub(crate) fn insert(&mut self, key: Key) -> bool {
|
||||||
if let Entry::Vacant(entry) = self.0.entry(key) {
|
if let Entry::Vacant(entry) = self.0.entry(key) {
|
||||||
entry.insert(());
|
entry.insert(());
|
||||||
true
|
true
|
||||||
@ -208,7 +179,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn contains(&self, key: &Key) -> bool {
|
pub(crate) fn contains(&self, key: &Key) -> bool {
|
||||||
self.0.contains_key(key)
|
self.0.contains_key(key)
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user