mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-06 10:11:44 +00:00
Simplify enum -> str with strum (#2164)
## Issue Addressed NA ## Proposed Changes As per #2100, uses derives from the sturm library to implement AsRef<str> and AsStaticRef to easily get str values from enums without creating new Strings. Furthermore unifies all attestation error counter into one IntCounterVec vector. These works are originally by @blacktemplar, I've just created this PR so I can resolve some merge conflicts. ## Additional Info NA Co-authored-by: blacktemplar <blacktemplar@a1.net>
This commit is contained in:
@@ -38,6 +38,7 @@ task_executor = { path = "../../common/task_executor" }
|
||||
rand = "0.7.3"
|
||||
directory = { path = "../../common/directory" }
|
||||
regex = "1.3.9"
|
||||
strum = { version = "0.20", features = ["derive"] }
|
||||
|
||||
[dependencies.libp2p]
|
||||
#version = "0.23.0"
|
||||
|
||||
@@ -437,7 +437,7 @@ impl<TSpec: EthSpec> Behaviour<TSpec> {
|
||||
.peers
|
||||
.read()
|
||||
.peer_info(propagation_source)
|
||||
.map(|info| info.client.kind.as_static_ref())
|
||||
.map(|info| info.client.kind.as_ref())
|
||||
{
|
||||
metrics::inc_counter_vec(
|
||||
&metrics::GOSSIP_UNACCEPTED_MESSAGES_PER_CLIENT,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use libp2p::identify::IdentifyInfo;
|
||||
use serde::Serialize;
|
||||
use strum::{AsRefStr, AsStaticStr};
|
||||
|
||||
/// Various client and protocol information related to a node.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
@@ -20,7 +21,7 @@ pub struct Client {
|
||||
pub agent_string: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, PartialEq)]
|
||||
#[derive(Clone, Debug, Serialize, PartialEq, AsRefStr, AsStaticStr)]
|
||||
pub enum ClientKind {
|
||||
/// A lighthouse node (the best kind).
|
||||
Lighthouse,
|
||||
@@ -98,26 +99,6 @@ impl std::fmt::Display for Client {
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientKind {
|
||||
pub fn as_static_ref(&self) -> &'static str {
|
||||
use ClientKind::*;
|
||||
match self {
|
||||
Lighthouse => "Lighthouse",
|
||||
Nimbus => "Nimbus",
|
||||
Teku => "Teku",
|
||||
Prysm => "Prysm",
|
||||
Lodestar => "Lodestar",
|
||||
Unknown => "Unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for ClientKind {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.as_static_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClientKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.as_ref())
|
||||
|
||||
@@ -158,8 +158,8 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
|
||||
metrics::inc_counter_vec(
|
||||
&metrics::PEER_ACTION_EVENTS_PER_CLIENT,
|
||||
&[
|
||||
info.client.kind.as_static_ref(),
|
||||
PeerAction::Fatal.as_static_str(),
|
||||
info.client.kind.as_ref(),
|
||||
PeerAction::Fatal.as_ref(),
|
||||
source.into(),
|
||||
],
|
||||
);
|
||||
@@ -193,11 +193,7 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
|
||||
info.apply_peer_action_to_score(action);
|
||||
metrics::inc_counter_vec(
|
||||
&metrics::PEER_ACTION_EVENTS_PER_CLIENT,
|
||||
&[
|
||||
info.client.kind.as_static_ref(),
|
||||
action.as_static_str(),
|
||||
source.into(),
|
||||
],
|
||||
&[info.client.kind.as_ref(), action.as_ref(), source.into()],
|
||||
);
|
||||
|
||||
Self::handle_score_transitions(
|
||||
@@ -407,9 +403,9 @@ impl<TSpec: EthSpec> PeerManager<TSpec> {
|
||||
metrics::inc_counter_vec(
|
||||
&metrics::TOTAL_RPC_ERRORS_PER_CLIENT,
|
||||
&[
|
||||
client.kind.as_static_ref(),
|
||||
client.kind.as_ref(),
|
||||
err.as_static_str(),
|
||||
direction.as_static_str(),
|
||||
direction.as_ref(),
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ use serde::{
|
||||
use std::collections::HashSet;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::time::Instant;
|
||||
use strum::AsRefStr;
|
||||
use types::{EthSpec, SubnetId};
|
||||
use PeerConnectionStatus::*;
|
||||
|
||||
@@ -320,21 +321,13 @@ impl Default for PeerStatus {
|
||||
}
|
||||
|
||||
/// Connection Direction of connection.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[derive(Debug, Clone, Serialize, AsRefStr)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum ConnectionDirection {
|
||||
Incoming,
|
||||
Outgoing,
|
||||
}
|
||||
|
||||
impl ConnectionDirection {
|
||||
pub fn as_static_str(&self) -> &'static str {
|
||||
match self {
|
||||
ConnectionDirection::Incoming => "incoming",
|
||||
ConnectionDirection::Outgoing => "outgoing",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connection Status of the peer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum PeerConnectionStatus {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use crate::behaviour::GOSSIPSUB_GREYLIST_THRESHOLD;
|
||||
use serde::Serialize;
|
||||
use std::time::Instant;
|
||||
use strum::AsRefStr;
|
||||
use tokio::time::Duration;
|
||||
|
||||
lazy_static! {
|
||||
@@ -42,7 +43,8 @@ const GOSSIPSUB_POSITIVE_SCORE_WEIGHT: f64 = GOSSIPSUB_NEGATIVE_SCORE_WEIGHT;
|
||||
/// Each variant has an associated score change.
|
||||
// To easily assess the behaviour of scores changes the number of variants should stay low, and
|
||||
// somewhat generic.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[derive(Debug, Clone, Copy, AsRefStr)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum PeerAction {
|
||||
/// We should not communicate more with this peer.
|
||||
/// This action will cause the peer to get banned.
|
||||
@@ -94,17 +96,6 @@ impl std::fmt::Display for PeerAction {
|
||||
}
|
||||
}
|
||||
|
||||
impl PeerAction {
|
||||
pub fn as_static_str(&self) -> &'static str {
|
||||
match self {
|
||||
PeerAction::HighToleranceError => "high_tolerance",
|
||||
PeerAction::MidToleranceError => "mid_tolerance",
|
||||
PeerAction::LowToleranceError => "low_tolerance",
|
||||
PeerAction::Fatal => "fatal",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The expected state of the peer given the peer's score.
|
||||
#[derive(Debug, PartialEq, Clone, Copy)]
|
||||
pub(crate) enum ScoreState {
|
||||
|
||||
@@ -9,6 +9,7 @@ use ssz_types::{
|
||||
VariableList,
|
||||
};
|
||||
use std::ops::Deref;
|
||||
use strum::AsStaticStr;
|
||||
use types::{Epoch, EthSpec, Hash256, SignedBeaconBlock, Slot};
|
||||
|
||||
/// Maximum number of blocks in a single request.
|
||||
@@ -257,7 +258,8 @@ pub enum RPCCodedResponse<T: EthSpec> {
|
||||
}
|
||||
|
||||
/// The code assigned to an erroneous `RPCResponse`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, AsStaticStr)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum RPCResponseErrorCode {
|
||||
RateLimited,
|
||||
InvalidRequest,
|
||||
|
||||
@@ -17,6 +17,7 @@ use ssz_types::VariableList;
|
||||
use std::io;
|
||||
use std::marker::PhantomData;
|
||||
use std::time::Duration;
|
||||
use strum::{AsStaticRef, AsStaticStr};
|
||||
use tokio_io_timeout::TimeoutStream;
|
||||
use tokio_util::{
|
||||
codec::Framed,
|
||||
@@ -470,10 +471,12 @@ where
|
||||
}
|
||||
|
||||
/// Error in RPC Encoding/Decoding.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[derive(Debug, Clone, PartialEq, AsStaticStr)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum RPCError {
|
||||
/// Error when decoding the raw buffer from ssz.
|
||||
// NOTE: in the future a ssz::DecodeError should map to an InvalidData error
|
||||
#[strum(serialize = "decode_error")]
|
||||
SSZDecodeError(ssz::DecodeError),
|
||||
/// IO Error.
|
||||
IoError(String),
|
||||
@@ -571,22 +574,8 @@ impl RPCError {
|
||||
/// Used for metrics.
|
||||
pub fn as_static_str(&self) -> &'static str {
|
||||
match self {
|
||||
RPCError::SSZDecodeError { .. } => "decode_error",
|
||||
RPCError::IoError { .. } => "io_error",
|
||||
RPCError::ErrorResponse(ref code, ..) => match code {
|
||||
RPCResponseErrorCode::RateLimited => "rate_limited",
|
||||
RPCResponseErrorCode::InvalidRequest => "invalid_request",
|
||||
RPCResponseErrorCode::ServerError => "server_error",
|
||||
RPCResponseErrorCode::ResourceUnavailable => "resource_unavailable",
|
||||
RPCResponseErrorCode::Unknown => "unknown_response_code",
|
||||
},
|
||||
RPCError::StreamTimeout => "stream_timeout",
|
||||
RPCError::UnsupportedProtocol => "unsupported_protocol",
|
||||
RPCError::IncompleteStream => "incomplete_stream",
|
||||
RPCError::InvalidData => "invalid_data",
|
||||
RPCError::InternalError { .. } => "internal_error",
|
||||
RPCError::NegotiationTimeout => "negotiation_timeout",
|
||||
RPCError::HandlerRejected => "handler_rejected",
|
||||
RPCError::ErrorResponse(ref code, ..) => code.as_static(),
|
||||
e => e.as_static(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use libp2p::gossipsub::{IdentTopic as Topic, TopicHash};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use strum::AsRefStr;
|
||||
use types::SubnetId;
|
||||
|
||||
/// The gossipsub topic names.
|
||||
@@ -36,13 +37,15 @@ pub struct GossipTopic {
|
||||
|
||||
/// Enum that brings these topics into the rust type system.
|
||||
// NOTE: There is intentionally no unknown type here. We only allow known gossipsub topics.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, AsRefStr)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum GossipKind {
|
||||
/// Topic for publishing beacon blocks.
|
||||
BeaconBlock,
|
||||
/// Topic for publishing aggregate attestations and proofs.
|
||||
/// Topic for publishing aggregate attestations and proofs.
|
||||
BeaconAggregateAndProof,
|
||||
/// Topic for publishing raw attestations on a particular subnet.
|
||||
#[strum(serialize = "beacon_attestation")]
|
||||
Attestation(SubnetId),
|
||||
/// Topic for publishing voluntary exits.
|
||||
VoluntaryExit,
|
||||
@@ -52,20 +55,6 @@ pub enum GossipKind {
|
||||
AttesterSlashing,
|
||||
}
|
||||
|
||||
impl AsRef<str> for GossipKind {
|
||||
fn as_ref(&self) -> &str {
|
||||
use GossipKind::*;
|
||||
match self {
|
||||
BeaconBlock => "beacon_block",
|
||||
BeaconAggregateAndProof => "beacon_aggregate_and_proof",
|
||||
Attestation(_) => "beacon_attestation",
|
||||
VoluntaryExit => "voluntary_exit",
|
||||
ProposerSlashing => "proposer_slashing",
|
||||
AttesterSlashing => "attester_slashing",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for GossipKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
@@ -310,4 +299,20 @@ mod tests {
|
||||
Some(SubnetId::new(42))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_as_str_ref() {
|
||||
assert_eq!("beacon_block", BeaconBlock.as_ref());
|
||||
assert_eq!(
|
||||
"beacon_aggregate_and_proof",
|
||||
BeaconAggregateAndProof.as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
"beacon_attestation",
|
||||
Attestation(SubnetId::new(42)).as_ref()
|
||||
);
|
||||
assert_eq!("voluntary_exit", VoluntaryExit.as_ref());
|
||||
assert_eq!("proposer_slashing", ProposerSlashing.as_ref());
|
||||
assert_eq!("attester_slashing", AttesterSlashing.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user