-
Notifications
You must be signed in to change notification settings - Fork 86
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
[ISSUE #983]🎨Optimize ConnectionHandler logic🔥 #984
Conversation
WalkthroughThe pull request introduces performance improvements to the Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
🚀Thanks for your contribution🎉. CodeRabbit(AI) will review your code first🔥 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Outside diff range and nitpick comments (3)
rocketmq-remoting/src/remoting_server/server.rs (3)
Line range hint
31-39
: Potential typo indo_after_rpc_hooks
method; should calldo_after_request
In the
do_after_rpc_hooks
method, you are callinghook.do_before_request(...)
, which appears to be a typo. Since this method is for executing hooks after the request is processed, it should callhook.do_after_request(...)
instead.Update the method as follows:
pub fn do_after_rpc_hooks( &self, channel: &Channel, response: &mut RemotingCommand, ) -> Result<()> { for hook in self.rpc_hooks.iter() { - hook.do_before_request(channel.remote_address(), response)?; + hook.do_after_request(channel.remote_address(), response)?; } Ok(()) }
Line range hint
199-253
: Simplify thehandle_error
function's control flowThe
handle_error
function contains nestedmatch
statements that can make the code harder to read and maintain. Refactoring the function to simplify the control flow can improve readability.Refactored
handle_error
function:async fn handle_error( &mut self, oneway_rpc: bool, opaque: i32, exception: Option<Error>, ) -> HandleErrorResult { if exception.is_none() { return HandleErrorResult::GoHead; } if oneway_rpc { return HandleErrorResult::Continue; } let exception_inner = exception.unwrap(); let response = match exception_inner { Error::AbortProcessException(code, message) => { RemotingCommand::create_response_command_with_code_remark(code, message) } _ => { RemotingCommand::create_response_command_with_code_remark( ResponseCode::SystemError, exception_inner.to_string(), ) } }; if let Err(err) = self .connection_handler_context .channel .connection .writer .send(response.set_opaque(opaque)) .await { if let Error::Io(io_error) = err { error!("Send response failed: {}", io_error); return HandleErrorResult::ReturnMethod; } else { error!("Send response failed: {}", err); } } HandleErrorResult::Continue }
186-191
: Improve error messages when sending responses failsProviding more detailed error messages can help with troubleshooting network issues or unexpected disconnections. Include the remote address in the log for better context.
Update the error handling as follows:
match err { Error::Io(io_error) => { - error!("connection disconnect: {}", io_error); + error!("Connection to {} disconnected: {}", self.channel.remote_address(), io_error); return Ok(()); } _ => { - error!("send response failed: {}", err); + error!("Failed to send response to {}: {}", self.channel.remote_address(), err); } }
Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Files selected for processing (2)
- rocketmq-remoting/src/protocol/remoting_command.rs (1 hunks)
- rocketmq-remoting/src/remoting_server/server.rs (3 hunks)
Additional comments not posted (2)
rocketmq-remoting/src/protocol/remoting_command.rs (2)
287-287
: Approved: Inliningset_opaque
method.The addition of the
#[inline]
attribute to theset_opaque
method is appropriate given its simplicity and potential frequency of use. Inlining can help reduce function call overhead, which aligns with the PR's objective to optimize performance.
293-293
: Approved: Inliningset_opaque_mut
method.The
#[inline]
attribute on theset_opaque_mut
method is beneficial for performance optimization. This method, due to its simplicity and potential high frequency of use, is an ideal candidate for inlining, which can effectively reduce the runtime overhead associated with function calls.
//handle error if return have | ||
match self.handle_error(oneway_rpc, opaque, exception).await { | ||
HandleErrorResult::Continue => continue, | ||
HandleErrorResult::ReturnMethod => return Ok(()), | ||
HandleErrorResult::GoHead => {} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reduce code duplication by refactoring error handling
The error handling blocks at lines 147-151 and 173-176 are nearly identical. Consider refactoring this repeated logic into a separate function to enhance maintainability and reduce duplication.
Example refactored code:
async fn process_handle_error(
&mut self,
oneway_rpc: bool,
opaque: i32,
exception: Option<Error>,
) -> Result<bool> {
match self.handle_error(oneway_rpc, opaque, exception).await {
HandleErrorResult::Continue => Ok(true),
HandleErrorResult::ReturnMethod => Ok(false),
HandleErrorResult::GoHead => Ok(false),
}
}
Then, replace the duplicated code with:
if self.process_handle_error(oneway_rpc, opaque, exception).await? {
continue;
}
Also applies to: 172-176
result = self.request_processor.process_request(channel,ctx,cmd) => match result{ | ||
Ok(value) => value, | ||
Err(_err) => Some(RemotingCommand::create_response_command_with_code( | ||
ResponseCode::SystemError, | ||
)), | ||
}, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Log errors from process_request
for better debugging
In the error case of process_request
, the error is currently ignored (Err(_err)
). Logging the error can aid in debugging and provide more context if issues arise.
Modify the code to log the error:
Err(err) => {
+ error!("Failed to process request: {}", err);
Some(RemotingCommand::create_response_command_with_code(
ResponseCode::SystemError,
))
},
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
result = self.request_processor.process_request(channel,ctx,cmd) => match result{ | |
Ok(value) => value, | |
Err(_err) => Some(RemotingCommand::create_response_command_with_code( | |
ResponseCode::SystemError, | |
)), | |
}, | |
result = self.request_processor.process_request(channel,ctx,cmd) => match result{ | |
Ok(value) => value, | |
Err(err) => { | |
error!("Failed to process request: {}", err); | |
Some(RemotingCommand::create_response_command_with_code( | |
ResponseCode::SystemError, | |
)) | |
}, | |
}, |
let exception = | ||
match self.do_before_rpc_hooks(&self.channel, response.as_mut().unwrap()) { | ||
Ok(_) => None, | ||
Err(error) => Some(error), | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incorrect use of do_before_rpc_hooks
; should be do_after_rpc_hooks
At line 167, after processing the request and generating the response, you are calling do_before_rpc_hooks
on the response. This seems incorrect, as do_before_rpc_hooks
is intended for processing before handling the request. You should use do_after_rpc_hooks
to process hooks after handling the response.
Apply this change:
- let exception = match self.do_before_rpc_hooks(&self.channel, response.as_mut().unwrap()) {
+ let exception = match self.do_after_rpc_hooks(&self.channel, response.as_mut().unwrap()) {
Ok(_) => None,
Err(error) => Some(error),
};
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
let exception = | |
match self.do_before_rpc_hooks(&self.channel, response.as_mut().unwrap()) { | |
Ok(_) => None, | |
Err(error) => Some(error), | |
}; | |
let exception = | |
match self.do_after_rpc_hooks(&self.channel, response.as_mut().unwrap()) { | |
Ok(_) => None, | |
Err(error) => Some(error), | |
}; |
Possible panic due to unwrap()
on response
when it is None
At line 167, you are calling response.as_mut().unwrap()
. If response
is None
, this will cause a panic at runtime. Since you check for response.is_none()
later at line 177, it's possible for response
to be None
.
Modify the code to safely handle the None
case:
- let exception = match self.do_after_rpc_hooks(&self.channel, response.as_mut().unwrap()) {
+ if let Some(ref mut resp) = response {
+ let exception = match self.do_after_rpc_hooks(&self.channel, resp) {
+ Ok(_) => None,
+ Err(error) => Some(error),
+ };
+ match self.handle_error(oneway_rpc, opaque, exception).await {
+ HandleErrorResult::Continue => continue,
+ HandleErrorResult::ReturnMethod => return Ok(()),
+ HandleErrorResult::GoHead => {}
+ }
+ } else if oneway_rpc {
+ continue;
+ } else {
+ // Handle the case where response is None and it's not a one-way RPC
+ // You might need to send an error response or log an error
+ // For example:
+ error!("Response is None for a non-one-way RPC");
+ return Ok(());
+ }
Committable suggestion was skipped due to low confidence.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #984 +/- ##
==========================================
- Coverage 19.84% 19.83% -0.02%
==========================================
Files 410 410
Lines 33633 33645 +12
==========================================
- Hits 6676 6674 -2
- Misses 26957 26971 +14 ☔ View full report in Codecov by Sentry. |
Which Issue(s) This PR Fixes(Closes)
Fixes #983
Brief Description
How Did You Test This Change?
Summary by CodeRabbit
New Features
Performance Improvements
set_opaque
andset_opaque_mut
methods in theRemotingCommand
struct.