Skip to content

Commit

Permalink
migrated to thiserror
Browse files Browse the repository at this point in the history
  • Loading branch information
pompon0 committed Apr 28, 2022
1 parent e520f29 commit 1fc80d7
Show file tree
Hide file tree
Showing 15 changed files with 337 additions and 208 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions chain/network/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ deepsize = { version = "0.2.0", optional = true }
futures = "0.3"
itertools = "0.10.3"
lru = "0.7.2"
thiserror = "1"
near-rust-allocator-proxy = { version = "0.4", optional = true }
once_cell = "1.5.2"
rand = "0.8.5"
Expand Down
60 changes: 0 additions & 60 deletions chain/network/src/network_protocol/borsh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,63 +220,3 @@ pub struct RoutingVersion2 {
pub(crate) edges: Vec<Edge>,
pub(crate) routing_state: RoutingState,
}

impl fmt::Display for PeerMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.msg_variant(), f)
}
}

impl PeerMessage {
pub(crate) fn msg_variant(&self) -> &str {
if let PeerMessage::Routed(routed_message) = self {
routed_message.body.as_ref()
} else {
self.as_ref()
}
}

pub(crate) fn is_client_message(&self) -> bool {
match self {
PeerMessage::Block(_)
| PeerMessage::BlockHeaders(_)
| PeerMessage::Challenge(_)
| PeerMessage::EpochSyncFinalizationResponse(_)
| PeerMessage::EpochSyncResponse(_)
| PeerMessage::Transaction(_) => true,
PeerMessage::Routed(r) => matches!(
r.body,
RoutedMessageBody::BlockApproval(_)
| RoutedMessageBody::ForwardTx(_)
| RoutedMessageBody::PartialEncodedChunk(_)
| RoutedMessageBody::PartialEncodedChunkForward(_)
| RoutedMessageBody::PartialEncodedChunkRequest(_)
| RoutedMessageBody::PartialEncodedChunkResponse(_)
| RoutedMessageBody::StateResponse(_)
| RoutedMessageBody::VersionedPartialEncodedChunk(_)
| RoutedMessageBody::VersionedStateResponse(_)
),
_ => false,
}
}

pub(crate) fn is_view_client_message(&self) -> bool {
match self {
PeerMessage::BlockHeadersRequest(_)
| PeerMessage::BlockRequest(_)
| PeerMessage::EpochSyncFinalizationRequest(_)
| PeerMessage::EpochSyncRequest(_) => true,
PeerMessage::Routed(r) => matches!(
r.body,
RoutedMessageBody::QueryRequest { .. }
| RoutedMessageBody::QueryResponse { .. }
| RoutedMessageBody::ReceiptOutcomeRequest(_)
| RoutedMessageBody::StateRequestHeader(_, _)
| RoutedMessageBody::StateRequestPart(_, _, _)
| RoutedMessageBody::TxStatusRequest(_, _)
| RoutedMessageBody::TxStatusResponse(_)
),
_ => false,
}
}
}
18 changes: 12 additions & 6 deletions chain/network/src/network_protocol/borsh_conv.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// Contains borsh <-> network_protocol conversions.
use crate::network_protocol as mem;
use crate::network_protocol::borsh as net;
use anyhow::bail;
use thiserror::Error;

impl From<&net::Handshake> for mem::Handshake {
fn from(x: &net::Handshake) -> Self {
Expand Down Expand Up @@ -75,13 +75,19 @@ impl From<&mem::HandshakeFailureReason> for net::HandshakeFailureReason {

//////////////////////////////////////////

#[derive(Error, Debug)]
pub enum ParsePeerMessageError {
#[error("HandshakeV2 is deprecated")]
DeprecatedHandshakeV2,
}

impl TryFrom<&net::PeerMessage> for mem::PeerMessage {
type Error = anyhow::Error;
fn try_from(x: &net::PeerMessage) -> anyhow::Result<Self> {
type Error = ParsePeerMessageError;
fn try_from(x: &net::PeerMessage) -> Result<Self, Self::Error> {
Ok(match x.clone() {
net::PeerMessage::Handshake(h) => mem::PeerMessage::Handshake((&h).try_into()?),
net::PeerMessage::Handshake(h) => mem::PeerMessage::Handshake((&h).into()),
net::PeerMessage::HandshakeFailure(pi, hfr) => {
mem::PeerMessage::HandshakeFailure(pi, (&hfr).try_into()?)
mem::PeerMessage::HandshakeFailure(pi, (&hfr).into())
}
net::PeerMessage::LastEdge(e) => mem::PeerMessage::LastEdge(e),
net::PeerMessage::SyncRoutingTable(rtu) => mem::PeerMessage::SyncRoutingTable(rtu),
Expand All @@ -99,7 +105,7 @@ impl TryFrom<&net::PeerMessage> for mem::PeerMessage {
net::PeerMessage::Routed(r) => mem::PeerMessage::Routed(r),
net::PeerMessage::Disconnect => mem::PeerMessage::Disconnect,
net::PeerMessage::Challenge(c) => mem::PeerMessage::Challenge(c),
net::PeerMessage::_HandshakeV2 => bail!("HandshakeV2 is deprecated"),
net::PeerMessage::_HandshakeV2 => return Err(Self::Error::DeprecatedHandshakeV2),
net::PeerMessage::EpochSyncRequest(epoch_id) => {
mem::PeerMessage::EpochSyncRequest(epoch_id)
}
Expand Down
36 changes: 28 additions & 8 deletions chain/network/src/network_protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use near_primitives::transaction::SignedTransaction;
use near_primitives::types::{EpochId, ProtocolVersion};
use near_primitives::version::PEER_MIN_ALLOWED_PROTOCOL_VERSION;
use std::fmt;
use thiserror::Error;

pub use self::borsh::{
PartialSync, RoutingState, RoutingSyncV2, RoutingTableUpdate, RoutingVersion2,
Expand Down Expand Up @@ -73,7 +74,7 @@ pub enum HandshakeFailureReason {
InvalidTarget,
}

#[derive(PartialEq, Eq, Clone, Debug, strum::AsStaticStr, strum::EnumVariantNames)]
#[derive(PartialEq, Eq, Clone, Debug, strum::AsRefStr, strum::EnumVariantNames)]
#[allow(clippy::large_enum_variant)]
pub enum PeerMessage {
Handshake(Handshake),
Expand Down Expand Up @@ -120,6 +121,18 @@ pub enum Encoding {
Proto,
}

#[derive(Error, Debug)]
pub enum ParsePeerMessageError {
#[error("BorshDecode")]
BorshDecode(std::io::Error),
#[error("BorshConv")]
BorshConv(borsh_conv::ParsePeerMessageError),
#[error("ProtoDecode")]
ProtoDecode(prost::DecodeError),
#[error("ProtoConv")]
ProtoConv(proto_conv::ParsePeerMessageError),
}

impl PeerMessage {
pub(crate) fn serialize(&self, enc: Encoding) -> Vec<u8> {
match enc {
Expand All @@ -128,19 +141,26 @@ impl PeerMessage {
}
}

pub(crate) fn deserialize(enc: Encoding, data: &[u8]) -> anyhow::Result<PeerMessage> {
pub(crate) fn deserialize(
enc: Encoding,
data: &[u8],
) -> Result<PeerMessage, ParsePeerMessageError> {
Ok(match enc {
Encoding::Borsh => (&borsh::PeerMessage::try_from_slice(data)?).try_into()?,
Encoding::Proto => (&proto::PeerMessage::decode(data)?).try_into()?,
Encoding::Borsh => (&borsh::PeerMessage::try_from_slice(data)
.map_err(ParsePeerMessageError::BorshDecode)?)
.try_into()
.map_err(ParsePeerMessageError::BorshConv)?,
Encoding::Proto => (&proto::PeerMessage::decode(data)
.map_err(ParsePeerMessageError::ProtoDecode)?)
.try_into()
.map_err(ParsePeerMessageError::ProtoConv)?,
})
}

pub(crate) fn msg_variant(&self) -> &str {
match self {
PeerMessage::Routed(routed_message) => {
strum::AsStaticRef::as_static(&routed_message.body)
}
_ => strum::AsStaticRef::as_static(self),
PeerMessage::Routed(routed_message) => routed_message.body.as_ref(),
_ => self.as_ref(),
}
}

Expand Down
Loading

0 comments on commit 1fc80d7

Please sign in to comment.