Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handlers refactoring #1567

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
dc81b16
routing_logic removal from common handlers and adaptations on roles
GitGab19 Mar 14, 2025
6d7a3fc
unused `parse_message` removal from common handlers
GitGab19 Mar 14, 2025
59a55b3
renaming of common handlers' traits to remove ambiguity
GitGab19 Mar 14, 2025
bccffa9
`Reconnect` message moved to common handlers
GitGab19 Mar 14, 2025
385b6ab
renaming of JD handlers' traits to remove ambiguity
GitGab19 Mar 14, 2025
d8333ed
renaming of TD (template-distribution) handlers' traits to remove amb…
GitGab19 Mar 14, 2025
b14aee8
`is_downstream_authorized` fn fixed to be implemented in roles
GitGab19 Mar 14, 2025
b1aa009
unused `get_request_id_mapper` fn removal from mining handlers and mi…
GitGab19 Mar 14, 2025
e0e64ef
`handle_set_group_channel` fn fixed to be implemented in roles
GitGab19 Mar 14, 2025
e91ebe3
renaming of mining handlers' traits to remove ambiguity
GitGab19 Mar 14, 2025
10e3d7f
routing_logic removal from ParseMiningMessagesFromDownstream and adap…
GitGab19 Mar 15, 2025
68314ea
routing_logic removal from ParseMiningMessagesFromUpstream and adapta…
GitGab19 Mar 15, 2025
36a5e6d
useless matches removal
GitGab19 Mar 17, 2025
d6b4821
SupportedChannelTypes moved back to mining handlers
GitGab19 Mar 18, 2025
ad25e79
Move info logs from common handlers to roles' implementations
GitGab19 Mar 20, 2025
a1ceafc
Move info logs from JD handlers to roles' implementations
GitGab19 Mar 20, 2025
d722fc7
Move info logs from TD handlers to roles' implementations
GitGab19 Mar 22, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions benches/benches/src/sv2/criterion_sv2_benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use criterion::{black_box, Criterion};
use roles_logic_sv2::{
handlers::{common::ParseUpstreamCommonMessages, mining::ParseUpstreamMiningMessages},
handlers::{common::ParseCommonMessagesFromUpstream, mining::ParseMiningMessagesFromUpstream},
parsers::{AnyMessage, Mining, MiningDeviceMessages},
routing_logic::{CommonRoutingLogic, MiningRoutingLogic},
utils::Mutex,
@@ -185,7 +185,7 @@ fn client_sv2_handle_message_common(c: &mut Criterion) {
let payload: &mut [u8] = &mut [payload];
c.bench_function("client_sv2_handle_message_common", |b| {
b.iter(|| {
black_box(ParseUpstreamCommonMessages::handle_message_common(
black_box(ParseCommonMessagesFromUpstream::handle_message_common(
self_.clone(),
message_type,
payload,
6 changes: 4 additions & 2 deletions benches/benches/src/sv2/iai_sv2_benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use codec_sv2::{StandardEitherFrame, StandardSv2Frame};
use iai::{black_box, main};
use roles_logic_sv2::{
handlers::{common::ParseUpstreamCommonMessages, mining::ParseUpstreamMiningMessages, SendTo_},
handlers::{
common::ParseCommonMessagesFromUpstream, mining::ParseMiningMessagesFromUpstream, SendTo_,
},
parsers::{AnyMessage, Mining, MiningDeviceMessages},
routing_logic::{CommonRoutingLogic, MiningRoutingLogic},
utils::Mutex,
@@ -152,7 +154,7 @@ fn client_sv2_handle_message_common() {
let message_type = u8::from_str_radix("8", 16).unwrap();
let payload: u8 = 200;
let payload: &mut [u8] = &mut [payload];
black_box(ParseUpstreamCommonMessages::handle_message_common(
black_box(ParseCommonMessagesFromUpstream::handle_message_common(
self_.clone(),
message_type,
payload,
8 changes: 4 additions & 4 deletions benches/benches/src/sv2/lib/client.rs
Original file line number Diff line number Diff line change
@@ -8,8 +8,8 @@ use roles_logic_sv2::{
common_properties::{IsMiningUpstream, IsUpstream},
errors::Error,
handlers::{
common::ParseUpstreamCommonMessages,
mining::{ParseUpstreamMiningMessages, SendTo, SupportedChannelTypes},
common::ParseCommonMessagesFromUpstream,
mining::{ParseMiningMessagesFromUpstream, SendTo, SupportedChannelTypes},
},
mining_sv2::*,
parsers::{Mining, MiningDeviceMessages},
@@ -71,7 +71,7 @@ impl SetupConnectionHandler {
}
}

impl ParseUpstreamCommonMessages<NoRouting> for SetupConnectionHandler {
impl ParseCommonMessagesFromUpstream<NoRouting> for SetupConnectionHandler {
fn handle_setup_connection_success(
&mut self,
_: SetupConnectionSuccess,
@@ -186,7 +186,7 @@ impl IsMiningUpstream<(), NullDownstreamMiningSelector> for Device {
}
}

impl ParseUpstreamMiningMessages<(), NullDownstreamMiningSelector, NoRouting> for Device {
impl ParseMiningMessagesFromUpstream<(), NullDownstreamMiningSelector, NoRouting> for Device {
fn get_channel_type(&self) -> SupportedChannelTypes {
SupportedChannelTypes::Standard
}
142 changes: 37 additions & 105 deletions protocols/v2/roles-logic-sv2/src/handlers/common.rs
Original file line number Diff line number Diff line change
@@ -25,27 +25,21 @@
//! Stratum V2 networks.

use super::SendTo_;
use crate::{
common_properties::CommonDownstreamData,
errors::Error,
parsers::CommonMessages,
routing_logic::{CommonRouter, CommonRoutingLogic},
utils::Mutex,
};
use crate::{errors::Error, parsers::CommonMessages, utils::Mutex};
use common_messages_sv2::{
ChannelEndpointChanged, SetupConnection, SetupConnectionError, SetupConnectionSuccess,
ChannelEndpointChanged, Reconnect, SetupConnection, SetupConnectionError,
SetupConnectionSuccess,
};
use const_sv2::*;
use core::convert::TryInto;
use std::sync::Arc;
use tracing::{debug, error, info, trace};

/// see [`SendTo_`]
pub type SendTo = SendTo_<CommonMessages<'static>, ()>;

/// A trait that is implemented by the downstream. It should be used to parse the common messages
/// that are sent from the upstream to the downstream.
pub trait ParseUpstreamCommonMessages<Router: CommonRouter>
/// A trait that is implemented by the downstream node, and is used to handle
/// common messages sent by the upstream to the downstream
pub trait ParseCommonMessagesFromUpstream
where
Self: Sized,
{
@@ -55,49 +49,28 @@ where
self_: Arc<Mutex<Self>>,
message_type: u8,
payload: &mut [u8],
routing_logic: CommonRoutingLogic<Router>,
) -> Result<SendTo, Error> {
Self::handle_message_common_deserilized(
self_,
(message_type, payload).try_into(),
routing_logic,
)
Self::handle_message_common_deserialized(self_, (message_type, payload).try_into())
}

/// Takes a message and it calls the appropriate handler function
fn handle_message_common_deserilized(
fn handle_message_common_deserialized(
self_: Arc<Mutex<Self>>,
message: Result<CommonMessages<'_>, Error>,
_routing_logic: CommonRoutingLogic<Router>,
) -> Result<SendTo, Error> {
match message {
Ok(CommonMessages::SetupConnectionSuccess(m)) => {
info!(
"Received SetupConnectionSuccess: version={}, flags={:b}",
m.used_version, m.flags
);
self_
.safe_lock(|x| x.handle_setup_connection_success(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?
}
Ok(CommonMessages::SetupConnectionError(m)) => {
error!(
"Received SetupConnectionError with error code {}",
std::str::from_utf8(m.error_code.as_ref()).unwrap_or("unknown error code")
);
self_
.safe_lock(|x| x.handle_setup_connection_error(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?
}
Ok(CommonMessages::ChannelEndpointChanged(m)) => {
info!(
"Received ChannelEndpointChanged with channel id: {}",
m.channel_id
);
self_
.safe_lock(|x| x.handle_channel_endpoint_changed(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?
}
Ok(CommonMessages::SetupConnectionSuccess(m)) => self_
.safe_lock(|x| x.handle_setup_connection_success(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
Ok(CommonMessages::SetupConnectionError(m)) => self_
.safe_lock(|x| x.handle_setup_connection_error(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
Ok(CommonMessages::ChannelEndpointChanged(m)) => self_
.safe_lock(|x| x.handle_channel_endpoint_changed(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
Ok(CommonMessages::Reconnect(m)) => self_
.safe_lock(|x| x.handle_reconnect(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
Ok(CommonMessages::SetupConnection(_)) => {
Err(Error::UnexpectedMessage(MESSAGE_TYPE_SETUP_CONNECTION))
}
@@ -128,88 +101,51 @@ where
&mut self,
m: ChannelEndpointChanged,
) -> Result<SendTo, Error>;

/// Handles a `Reconnect` message.
fn handle_reconnect(&mut self, m: Reconnect) -> Result<SendTo, Error>;
}

/// A trait that is implemented by the upstream node, and is used to handle
/// [`crate::parsers::CommonMessages::SetupConnection`] messages sent by the downstream to the
/// upstream
pub trait ParseDownstreamCommonMessages<Router: CommonRouter>
/// common messages sent by the downstream to the upstream
pub trait ParseCommonMessagesFromDownstream
where
Self: Sized,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need Sized for the entire trait or only for specific methods? In this case, requiring Sized for handle_message_common and handle_message_common_deserialized is sufficient.

{
/// Used to parse a serialized downstream setup connection message into a
/// [`crate::parsers::CommonMessages::SetupConnection`]
fn parse_message(message_type: u8, payload: &mut [u8]) -> Result<SetupConnection, Error> {
match (message_type, payload).try_into() {
Ok(CommonMessages::SetupConnection(m)) => Ok(m),
Ok(CommonMessages::SetupConnectionSuccess(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_SETUP_CONNECTION_SUCCESS,
)),
Ok(CommonMessages::SetupConnectionError(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_SETUP_CONNECTION_ERROR,
)),
Ok(CommonMessages::ChannelEndpointChanged(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_CHANNEL_ENDPOINT_CHANGED,
)),
Err(e) => Err(e),
}
}

/// It takes a message type and a payload, and if the message is a serialized setup connection
/// message, it calls the `on_setup_connection` function on the routing logic, and then calls
/// the `handle_setup_connection` function on the router
fn handle_message_common(
self_: Arc<Mutex<Self>>,
message_type: u8,
payload: &mut [u8],
routing_logic: CommonRoutingLogic<Router>,
) -> Result<SendTo, Error> {
Self::handle_message_common_deserilized(
self_,
(message_type, payload).try_into(),
routing_logic,
)
Self::handle_message_common_deserialized(self_, (message_type, payload).try_into())
}

/// It takes a message do setup connection message, it calls
/// the `on_setup_connection` function on the routing logic, and then calls
/// the `handle_setup_connection` function on the router
fn handle_message_common_deserilized(
fn handle_message_common_deserialized(
self_: Arc<Mutex<Self>>,
message: Result<CommonMessages<'_>, Error>,
routing_logic: CommonRoutingLogic<Router>,
) -> Result<SendTo, Error> {
match message {
Ok(CommonMessages::SetupConnection(m)) => {
info!(
"Received SetupConnection: version={}, flags={:b}",
m.min_version, m.flags
);
debug!("Setup connection message: {:?}", m);
match routing_logic {
CommonRoutingLogic::Proxy(r_logic) => {
trace!("On SetupConnection r_logic is {:?}", r_logic);
let result = r_logic
.safe_lock(|r_logic| r_logic.on_setup_connection(&m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?;
self_
.safe_lock(|x| x.handle_setup_connection(m, Some(result)))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?
}
CommonRoutingLogic::None => self_
.safe_lock(|x| x.handle_setup_connection(m, None))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
}
}
Ok(CommonMessages::SetupConnection(m)) => self_
.safe_lock(|x| x.handle_setup_connection(m))
.map_err(|e| crate::Error::PoisonLock(e.to_string()))?,
Ok(CommonMessages::SetupConnectionSuccess(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_SETUP_CONNECTION_SUCCESS,
MESSAGE_TYPE_SETUP_CONNECTION_SUCCESS,
)),
Ok(CommonMessages::SetupConnectionError(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_SETUP_CONNECTION_ERROR,
MESSAGE_TYPE_SETUP_CONNECTION_ERROR,
)),
Ok(CommonMessages::ChannelEndpointChanged(_)) => Err(Error::UnexpectedMessage(
const_sv2::MESSAGE_TYPE_CHANNEL_ENDPOINT_CHANGED,
MESSAGE_TYPE_CHANNEL_ENDPOINT_CHANGED,
)),
Ok(CommonMessages::Reconnect(_)) => {
Err(Error::UnexpectedMessage(MESSAGE_TYPE_RECONNECT))
}
Err(e) => Err(e),
}
}
@@ -218,9 +154,5 @@ where
///
/// This method processes a `SetupConnection` message and handles it
/// by delegating to the appropriate handler in the routing logic.
fn handle_setup_connection(
&mut self,
m: SetupConnection,
result: Option<Result<(CommonDownstreamData, SetupConnectionSuccess), Error>>,
) -> Result<SendTo, Error>;
fn handle_setup_connection(&mut self, m: SetupConnection) -> Result<SendTo, Error>;
}
Loading