Skip to content

[ISSUE #1285]⚡️Optimize name server ClientRequestProcessor#get_route_info_by_topic #1286

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

Merged
merged 1 commit into from
Nov 24, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Nov 24, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1285

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Enhanced error handling and logging for broker registration and deregistration processes.
    • Introduced a read lock mechanism for thread-safe access to route data.
  • Bug Fixes

    • Improved error handling in the request header decoding process.
  • Documentation

    • Updated method signatures to reflect new error handling and concurrency improvements.

Copy link
Contributor

coderabbitai bot commented Nov 24, 2024

Walkthrough

The changes in this pull request involve modifications to the ClientRequestProcessor and RouteInfoManager within the RocketMQ nameserver. Key updates include improved error handling in the get_route_info_by_topic method, where expect replaces unwrap for better clarity in failure cases. Additionally, atomic operations for the readiness flag have been refined for enhanced synchronization. In the RouteInfoManager, a read lock was added for thread-safe data access, and methods for broker registration and deregistration were updated to include better error handling and logging.

Changes

File Path Change Summary
rocketmq-namesrv/src/processor/client_request_processor.rs Modified get_route_info_by_topic to use expect for error handling; updated atomic operations for need_check_namesrv_ready.
rocketmq-namesrv/src/route/route_info_manager.rs Added read lock in pickup_topic_route_data; enhanced error handling in register_broker and improved deregistration in un_register_broker.

Possibly related PRs

Suggested labels

enhancement, approved, auto merge, AI review first

Suggested reviewers

  • TeslaRustor
  • SpaceXCN

🐰 In the land of code so bright,
Changes made to set things right.
With locks and checks, we pave the way,
For robust systems, come what may!
Error handling, clear and neat,
A hop towards success, oh what a treat! 🌟


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.

@rocketmq-rust-bot rocketmq-rust-bot added this to the v0.4.0 milestone Nov 24, 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 24, 2024

Codecov Report

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

Project coverage is 18.97%. Comparing base (4445013) to head (fa580cf).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...-namesrv/src/processor/client_request_processor.rs 0.00% 4 Missing ⚠️
rocketmq-namesrv/src/route/route_info_manager.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1286      +/-   ##
==========================================
- Coverage   18.98%   18.97%   -0.01%     
==========================================
  Files         428      428              
  Lines       53863    53868       +5     
==========================================
  Hits        10224    10224              
- Misses      43639    43644       +5     

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


🚨 Try these New Features:

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: 2

🧹 Outside diff range and nitpick comments (1)
rocketmq-namesrv/src/route/route_info_manager.rs (1)

Line range hint 388-420: Optimize the scope of the read lock in pickup_topic_route_data

The read lock lock is acquired at line 388 and explicitly dropped at line 420. To make the code cleaner and ensure the lock is held for the minimal necessary duration, consider using a scoped block. This way, the lock is automatically released when it goes out of scope, eliminating the need for an explicit drop(lock);.

Apply this refactor to enhance clarity and safety:

pub(crate) fn pickup_topic_route_data(&self, topic: &CheetahString) -> Option<TopicRouteData> {
    let mut topic_route_data = TopicRouteData {
        order_topic_conf: None,
        broker_datas: Vec::new(),
        queue_datas: Vec::new(),
        filter_server_table: HashMap::new(),
        topic_queue_mapping_by_broker: None,
    };

    let mut found_queue_data = false;
    let mut found_broker_data = false;

+   {
        // Acquire read lock within a scoped block
        let lock = self.lock.read();
        if let Some(queue_data_map) = self.topic_queue_table.get(topic) {
            topic_route_data.queue_datas = queue_data_map.values().cloned().collect();
            found_queue_data = true;

            for broker_name in queue_data_map.keys() {
                if let Some(broker_data) = self.broker_addr_table.get(broker_name) {
                    let broker_data_clone = broker_data.clone();
                    topic_route_data.broker_datas.push(broker_data_clone);
                    found_broker_data = true;

                    if !self.filter_server_table.is_empty() {
                        for broker_addr in broker_data.broker_addrs().values() {
                            let broker_addr_info =
                                BrokerAddrInfo::new(broker_data.cluster(), broker_addr.clone());
                            if let Some(filter_server_list) =
                                self.filter_server_table.get(&broker_addr_info)
                            {
                                topic_route_data.filter_server_table.insert(
                                    broker_addr.clone(),
                                    filter_server_list
                                        .clone()
                                        .into_iter()
                                        .map(CheetahString::from_string)
                                        .collect(),
                                );
                            }
                        }
                    }
                }
            }
        }
-       drop(lock);
+   } // Lock is automatically released here

    debug!("pickup_topic_route_data {:?} {:?}", topic, topic_route_data);

    if found_broker_data && found_queue_data {
        topic_route_data.topic_queue_mapping_by_broker =
            self.topic_queue_mapping_info_table.get(topic).cloned();

        if !self.namesrv_config.support_acting_master {
            return Some(topic_route_data);
        }

        // ... rest of the method remains unchanged
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4445013 and fa580cf.

📒 Files selected for processing (2)
  • rocketmq-namesrv/src/processor/client_request_processor.rs (2 hunks)
  • rocketmq-namesrv/src/route/route_info_manager.rs (2 hunks)
🔇 Additional comments (1)
rocketmq-namesrv/src/processor/client_request_processor.rs (1)

Line range hint 103-115: Address commented-out version-specific JSON handling

The commented code suggests there should be different JSON handling based on RocketMQ versions and accept_standard_json_only flag. This functionality appears to be missing.

Let's check if this is handled elsewhere:

Would you like help implementing the version-specific JSON handling?

Comment on lines +93 to +95
if self.need_check_namesrv_ready.load(Ordering::Acquire) {
self.need_check_namesrv_ready
.store(false, Ordering::Release);
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

Fix inconsistent memory ordering for need_check_namesrv_ready

There's an inconsistency in the atomic ordering used for need_check_namesrv_ready:

  • Line 68 uses Ordering::Relaxed
  • Line 93 uses Ordering::Acquire

This could lead to visibility issues across threads. Consider using consistent memory ordering.

-        let namesrv_ready = self.need_check_namesrv_ready.load(Ordering::Relaxed)
+        let namesrv_ready = self.need_check_namesrv_ready.load(Ordering::Acquire)

Committable suggestion skipped: line range outside the PR's diff.

@@ -64,7 +64,7 @@
fn get_route_info_by_topic(&self, request: RemotingCommand) -> RemotingCommand {
let request_header = request
.decode_command_custom_header::<GetRouteInfoRequestHeader>()
.unwrap();
.expect("GetRouteInfoRequestHeader failed");
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using proper error handling instead of expect

While expect is more informative than unwrap, panicking in a server context can be disruptive. Consider handling the decoding error gracefully by returning an error response to the client.

-            .expect("GetRouteInfoRequestHeader failed");
+            .map_err(|_| RemotingCommand::create_response_command_with_code(
+                RemotingSysResponseCode::SystemError
+            ).set_remark("Failed to decode GetRouteInfoRequestHeader"))?;

Committable suggestion skipped: line range outside the PR's diff.

@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved auto merge and removed ready to review waiting-review waiting review this PR labels Nov 24, 2024
@rocketmq-rust-bot rocketmq-rust-bot merged commit 86a9d6d into main Nov 24, 2024
28 of 29 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added the enhancement⚡️ New feature or request label Nov 24, 2024
@mxsm mxsm deleted the op-1285 branch November 25, 2024 14:10
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 enhancement⚡️ New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Enhancement⚡️] Optimize name server ClientRequestProcessor#get_route_info_by_topic
3 participants