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

[ISSUE #1364]🍻Broker Supports request code SetMessageRequestMode (401) #1365

Merged
merged 1 commit into from
Nov 27, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Nov 27, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1364

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Enhanced request handling for setting message modes, including improved error handling and permission checks based on topic prefixes.
    • Introduced specific responses for restricted topics to prevent unauthorized mode settings.
  • Bug Fixes

    • Improved decoding logic for request bodies to prevent panics during processing.

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The pull request introduces significant updates to the QueryAssignmentProcessor struct in the rocketmq-broker/src/processor/query_assignment_processor.rs file. The set_message_request_mode method has been modified to decode a request body and handle specific conditions based on the topic. It includes error handling for decoding failures and checks for a restricted prefix in the topic name, influencing the response. If the topic is valid, it updates the message request mode and persists the changes.

Changes

File Path Change Summary
rocketmq-broker/src/processor/query_assignment_processor.rs Updated set_message_request_mode method to decode request body, handle errors, and manage topic permissions.

Assessment against linked issues

Objective Addressed Explanation
Broker Supports request code SetMessageRequestMode (401)

Possibly related PRs

Suggested labels

feature, approved, auto merge, AI review first

Suggested reviewers

  • SpaceXCN
  • TeslaRustor

🐰 In the code, we hop and play,
With messages sent on their way.
A mode to set, with care we write,
Permissions checked, all feels right!
So let us code, with joy and cheer,
For every change, we hold so dear! 🌟


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@RocketmqRustBot RocketmqRustBot added the feature🚀 Suggest an idea for this project. label Nov 27, 2024
@RocketmqRustBot RocketmqRustBot added this to the v0.4.0 milestone Nov 27, 2024
@rocketmq-rust-bot
Copy link
Collaborator

🔊@mxsm 🚀Thanks for your contribution 🎉. CodeRabbit(AI) will review your code first 🔥

Copy link

codecov bot commented Nov 27, 2024

Codecov Report

Attention: Patch coverage is 0% with 21 lines in your changes missing coverage. Please review.

Project coverage is 21.03%. Comparing base (f4d96f9) to head (2fc62ea).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...broker/src/processor/query_assignment_processor.rs 0.00% 21 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1365      +/-   ##
==========================================
- Coverage   21.04%   21.03%   -0.01%     
==========================================
  Files         434      434              
  Lines       55171    55191      +20     
==========================================
  Hits        11611    11611              
- Misses      43560    43580      +20     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
rocketmq-broker/src/processor/query_assignment_processor.rs (1)

101-108: Use precise response code for invalid topic

Returning NoPermission may not accurately reflect the issue when a retry topic is not allowed. Consider using a more specific response code like TopicNotAllowed or BadRequest if available.

Implementing a more precise response code enhances clarity for the client about why the request was rejected.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f4d96f9 and 2fc62ea.

📒 Files selected for processing (1)
  • rocketmq-broker/src/processor/query_assignment_processor.rs (2 hunks)
🔇 Additional comments (3)
rocketmq-broker/src/processor/query_assignment_processor.rs (3)

30-33: Necessary imports added for new functionality

The additional use statements are appropriate and required for the implemented changes in the set_message_request_mode method.


109-114: Ensure thread-safe access to shared resources

The message_request_mode_manager is being modified and persisted. If multiple threads can access this method concurrently, there might be race conditions.

Verify that message_request_mode_manager is protected with synchronization primitives like Mutex or RwLock to ensure thread safety.


115-117: Confirm appropriate success response

Returning ResponseCode::Success after persisting changes is appropriate. Ensure that this aligns with the client's expectations and the overall protocol design.

Comment on lines +96 to +117
request: RemotingCommand,
) -> Option<RemotingCommand> {
unimplemented!()
let request_body =
SetMessageRequestModeRequestBody::decode(request.get_body().expect("empty body"))
.expect("decode SetMessageRequestModeRequestBody failed");
if request_body.topic.starts_with(RETRY_GROUP_TOPIC_PREFIX) {
return Some(
RemotingCommand::create_response_command_with_code(ResponseCode::NoPermission)
.set_remark(CheetahString::from_static_str(
"retry topic is not allowed to set mode",
)),
);
}
self.message_request_mode_manager.set_message_request_mode(
request_body.topic.clone(),
request_body.consumer_group.clone(),
request_body,
);
self.message_request_mode_manager.persist();
Some(RemotingCommand::create_response_command_with_code(
ResponseCode::Success,
))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential errors without panicking

Using .expect() for error handling can cause the program to panic if an error occurs. It's better to handle errors gracefully and return an appropriate response to the client.

Apply the following changes to handle errors more gracefully:

 async fn set_message_request_mode(
     &mut self,
     _channel: Channel,
     _ctx: ConnectionHandlerContext,
     request: RemotingCommand,
 ) -> Option<RemotingCommand> {
-    let request_body =
-        SetMessageRequestModeRequestBody::decode(request.get_body().expect("empty body"))
-            .expect("decode SetMessageRequestModeRequestBody failed");
+    let request_body = match request.get_body() {
+        Some(body) => match SetMessageRequestModeRequestBody::decode(body) {
+            Ok(decoded_body) => decoded_body,
+            Err(_) => {
+                return Some(
+                    RemotingCommand::create_response_command_with_code(ResponseCode::BadRequest)
+                        .set_remark(CheetahString::from_static_str("Failed to decode request body")),
+                );
+            }
+        },
+        None => {
+            return Some(
+                RemotingCommand::create_response_command_with_code(ResponseCode::BadRequest)
+                    .set_remark(CheetahString::from_static_str("Empty request body")),
+            );
+        }
+    };

This modification ensures that decoding errors are handled appropriately, and informative responses are sent back to the client without causing a panic.

📝 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.

Suggested change
request: RemotingCommand,
) -> Option<RemotingCommand> {
unimplemented!()
let request_body =
SetMessageRequestModeRequestBody::decode(request.get_body().expect("empty body"))
.expect("decode SetMessageRequestModeRequestBody failed");
if request_body.topic.starts_with(RETRY_GROUP_TOPIC_PREFIX) {
return Some(
RemotingCommand::create_response_command_with_code(ResponseCode::NoPermission)
.set_remark(CheetahString::from_static_str(
"retry topic is not allowed to set mode",
)),
);
}
self.message_request_mode_manager.set_message_request_mode(
request_body.topic.clone(),
request_body.consumer_group.clone(),
request_body,
);
self.message_request_mode_manager.persist();
Some(RemotingCommand::create_response_command_with_code(
ResponseCode::Success,
))
request: RemotingCommand,
) -> Option<RemotingCommand> {
let request_body = match request.get_body() {
Some(body) => match SetMessageRequestModeRequestBody::decode(body) {
Ok(decoded_body) => decoded_body,
Err(_) => {
return Some(
RemotingCommand::create_response_command_with_code(ResponseCode::BadRequest)
.set_remark(CheetahString::from_static_str("Failed to decode request body")),
);
}
},
None => {
return Some(
RemotingCommand::create_response_command_with_code(ResponseCode::BadRequest)
.set_remark(CheetahString::from_static_str("Empty request body")),
);
}
};
if request_body.topic.starts_with(RETRY_GROUP_TOPIC_PREFIX) {
return Some(
RemotingCommand::create_response_command_with_code(ResponseCode::NoPermission)
.set_remark(CheetahString::from_static_str(
"retry topic is not allowed to set mode",
)),
);
}
self.message_request_mode_manager.set_message_request_mode(
request_body.topic.clone(),
request_body.consumer_group.clone(),
request_body,
);
self.message_request_mode_manager.persist();
Some(RemotingCommand::create_response_command_with_code(
ResponseCode::Success,
))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
AI review first Ai review pr first approved PR has approved auto merge feature🚀 Suggest an idea for this project.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀] Broker Supports request code SetMessageRequestMode (401)
4 participants