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

feat/91: Add get namesrv config request #1485

Merged
merged 4 commits into from
Dec 1, 2024

Conversation

PanGan21
Copy link
Contributor

@PanGan21 PanGan21 commented Dec 1, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #91

Brief Description

Adds get namsrv config request

How Did You Test This Change?

Unit tests

Summary by CodeRabbit

  • New Features

    • Introduced a method to retrieve nameserver configuration as a formatted string.
    • Added serialization support for configuration data, allowing export in JSON format.
  • Bug Fixes

    • Enhanced error handling for configuration retrieval and serialization processes.
  • Tests

    • Added a test case to ensure the new configuration retrieval method produces valid JSON output.

Copy link
Contributor

coderabbitai bot commented Dec 1, 2024

Walkthrough

The pull request introduces enhancements to the NamesrvConfig struct by implementing the Serialize trait for JSON serialization and adding a method to retrieve configuration values as a formatted string. Additionally, it updates the DefaultRequestProcessor to handle a new request code for fetching nameserver configuration. This involves adding a new method and modifying the existing request processing logic to accommodate the new functionality, while maintaining the overall structure and integrity of the existing code.

Changes

File Path Change Summary
rocketmq-common/src/common/namesrv/namesrv_config.rs - Added Serialize trait to NamesrvConfig.
- Introduced method get_all_configs_format_string(&self).
- Added a test case for the new method.
rocketmq-namesrv/src/processor/default_request_processor.rs - Added method get_config to handle RequestCode::GetNamesrvConfig.
- Updated process_request to include the new request handling.

Assessment against linked issues

Objective Addressed Explanation
Support for getting nameserver configuration (Issue #91)

Possibly related PRs

  • [ISSUE #90]Support update namesrv config #1316: The changes in this PR involve adding support for updating the Namesrv configuration, which directly relates to the modifications made to the NamesrvConfig struct in the main PR, particularly the new update method that allows for modifying configuration properties.

Suggested labels

approved

Suggested reviewers

  • TeslaRustor
  • mxsm

Poem

In the code where rabbits play,
New features hop and dance today.
Configs serialized, neat and bright,
Namesrv fetches with delight!
A joyful leap in every line,
Enhancements made, all is fine! 🐇✨


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-robot rocketmq-rust-robot added this to the v0.4.0 milestone Dec 1, 2024
@rocketmq-rust-bot
Copy link
Collaborator

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

@rocketmq-rust-robot rocketmq-rust-robot added enhancement⚡️ New feature or request feature🚀 Suggest an idea for this project. good first issue Good for newcomers help wanted Extra attention is needed labels Dec 1, 2024
pub fn get_all_configs_format_string(&self) -> Result<String, String> {
let mut json_map = HashMap::new();

json_map.insert(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This can be improved if we replace #[serde(alias = "property")] with #[serde(rename = "property")].
Then we can use serde_json here, but I am not sure how many things this change would break.

@rocketmq-rust-bot
Copy link
Collaborator

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

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-common/src/common/namesrv/namesrv_config.rs (1)

152-248: Consider simplifying the implementation using direct serialization.

The current implementation manually constructs a HashMap and converts each field. Since the struct already derives Serialize, you could simplify this by directly serializing the struct instance.

Consider this simpler implementation:

-    pub fn get_all_configs_format_string(&self) -> Result<String, String> {
-        let mut json_map = HashMap::new();
-
-        json_map.insert(
-            "rocketmqHome".to_string(),
-            Value::String(self.rocketmq_home.clone()),
-        );
-        // ... (removed other insertions for brevity)
-
-        // Convert the HashMap to a JSON value
-        match serde_json::to_string_pretty(&json_map) {
-            Ok(json) => Ok(json),
-            Err(err) => {
-                return Err(format!("Failed to serialize NamesrvConfig: {}", err));
-            }
-        }
-    }
+    pub fn get_all_configs_format_string(&self) -> Result<String, String> {
+        serde_json::to_string_pretty(self)
+            .map_err(|err| format!("Failed to serialize NamesrvConfig: {}", err))
+    }

This approach:

  • Leverages the derived Serialize implementation
  • Reduces code duplication
  • Maintains the same functionality
  • Is less prone to errors when struct fields change
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2f5f0c6 and 79f85b6.

📒 Files selected for processing (2)
  • rocketmq-common/src/common/namesrv/namesrv_config.rs (3 hunks)
  • rocketmq-namesrv/src/processor/default_request_processor.rs (2 hunks)
🔇 Additional comments (3)
rocketmq-common/src/common/namesrv/namesrv_config.rs (2)

23-23: LGTM: Serialize trait addition is correct.

The addition of the Serialize trait is appropriate for enabling JSON serialization of the NamesrvConfig struct.

Also applies to: 29-29


538-604: LGTM: Comprehensive test coverage.

The test case thoroughly verifies:

  • JSON serialization success
  • Non-empty output
  • Correct serialization of all config fields
rocketmq-namesrv/src/processor/default_request_processor.rs (1)

109-109: LGTM: Request code handling is correctly implemented.

The addition of RequestCode::GetNamesrvConfig handler is consistent with the existing pattern and correctly maps to the new get_config method.

Comment on lines 492 to 507
fn get_config(&mut self, _request: RemotingCommand) -> RemotingCommand {
let config = self.kvconfig_manager.get_namesrv_config();
match config.get_all_configs_format_string() {
Ok(content) => {
let response = RemotingCommand::create_response_command_with_code_remark(
RemotingSysResponseCode::Success,
CheetahString::empty(),
);
response.set_body(content.into_bytes())
}
Err(e) => RemotingCommand::create_response_command_with_code_remark(
ResponseCode::SystemError,
format!("UnsupportedEncodingException " + e),
),
}
}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 1, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix string concatenation in error message.

The error message formatting uses the + operator which is less idiomatic in Rust.

Apply this change:

             Err(e) => RemotingCommand::create_response_command_with_code_remark(
                 ResponseCode::SystemError,
-                format!("UnsupportedEncodingException " + e),
+                format!("UnsupportedEncodingException {}", e),
             ),

This change:

  • Uses the more idiomatic string formatting in Rust
  • Maintains the same error message content
  • Is consistent with other error handling in the codebase
📝 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
fn get_config(&mut self, _request: RemotingCommand) -> RemotingCommand {
let config = self.kvconfig_manager.get_namesrv_config();
match config.get_all_configs_format_string() {
Ok(content) => {
let response = RemotingCommand::create_response_command_with_code_remark(
RemotingSysResponseCode::Success,
CheetahString::empty(),
);
response.set_body(content.into_bytes())
}
Err(e) => RemotingCommand::create_response_command_with_code_remark(
ResponseCode::SystemError,
format!("UnsupportedEncodingException " + e),
),
}
}
fn get_config(&mut self, _request: RemotingCommand) -> RemotingCommand {
let config = self.kvconfig_manager.get_namesrv_config();
match config.get_all_configs_format_string() {
Ok(content) => {
let response = RemotingCommand::create_response_command_with_code_remark(
RemotingSysResponseCode::Success,
CheetahString::empty(),
);
response.set_body(content.into_bytes())
}
Err(e) => RemotingCommand::create_response_command_with_code_remark(
ResponseCode::SystemError,
format!("UnsupportedEncodingException {}", e),
),
}
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed

Copy link
Contributor

Choose a reason for hiding this comment

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

@PanGan21, great to hear that you've fixed the issue!

(_/)
(•_•)
/ >🎉


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@rocketmq-rust-bot
Copy link
Collaborator

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

@rocketmq-rust-bot
Copy link
Collaborator

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

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-common/src/common/namesrv/namesrv_config.rs (1)

535-601: Enhance test coverage

The test thoroughly verifies successful serialization but could be improved with additional test cases.

Consider adding:

  1. Error case testing:
#[test]
fn test_get_all_configs_format_string_error() {
    // Mock a scenario that would cause serialization to fail
    // This might require creating a test-specific struct with custom serialization
    // that always fails
}
  1. Use test constants for better maintainability:
#[cfg(test)]
mod tests {
    const TEST_CONFIG: &str = r#"{
        "rocketmqHome": "/path/to/home",
        "kvConfigPath": "/path/to/kv",
        // ... other fields ...
    }"#;
    
    #[test]
    fn test_get_all_configs_format_string_matches_expected() {
        let config = NamesrvConfig::new();
        let json_output = config.get_all_configs_format_string().unwrap();
        
        // Compare with expected format
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&json_output).unwrap(),
            serde_json::from_str::<serde_json::Value>(TEST_CONFIG).unwrap()
        );
    }
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 79f85b6 and 0111bc9.

📒 Files selected for processing (2)
  • rocketmq-common/src/common/namesrv/namesrv_config.rs (3 hunks)
  • rocketmq-namesrv/src/processor/default_request_processor.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rocketmq-namesrv/src/processor/default_request_processor.rs
🔇 Additional comments (2)
rocketmq-common/src/common/namesrv/namesrv_config.rs (2)

23-23: LGTM!

The serde_json::Value import is appropriately placed and necessary for the new configuration serialization functionality.


Line range hint 29-29: Consider using serde(rename) instead of serde(alias)

As mentioned in a previous review, consider replacing #[serde(alias = "property")] with #[serde(rename = "property")] throughout the struct. This would allow using serde_json directly and potentially simplify the implementation.

Comment on lines +151 to +245
pub fn get_all_configs_format_string(&self) -> Result<String, String> {
let mut json_map = HashMap::new();

json_map.insert(
"rocketmqHome".to_string(),
Value::String(self.rocketmq_home.clone()),
);
json_map.insert(
"kvConfigPath".to_string(),
Value::String(self.kv_config_path.clone()),
);
json_map.insert(
"configStorePath".to_string(),
Value::String(self.config_store_path.clone()),
);
json_map.insert(
"productEnvName".to_string(),
Value::String(self.product_env_name.clone()),
);
json_map.insert("clusterTest".to_string(), Value::Bool(self.cluster_test));
json_map.insert(
"orderMessageEnable".to_string(),
Value::Bool(self.order_message_enable),
);
json_map.insert(
"returnOrderTopicConfigToBroker".to_string(),
Value::Bool(self.return_order_topic_config_to_broker),
);
json_map.insert(
"clientRequestThreadPoolNums".to_string(),
Value::Number(self.client_request_thread_pool_nums.into()),
);
json_map.insert(
"defaultThreadPoolNums".to_string(),
Value::Number(self.default_thread_pool_nums.into()),
);
json_map.insert(
"clientRequestThreadPoolQueueCapacity".to_string(),
Value::Number(self.client_request_thread_pool_queue_capacity.into()),
);
json_map.insert(
"defaultThreadPoolQueueCapacity".to_string(),
Value::Number(self.default_thread_pool_queue_capacity.into()),
);
json_map.insert(
"scanNotActiveBrokerInterval".to_string(),
Value::Number(self.scan_not_active_broker_interval.into()),
);
json_map.insert(
"unRegisterBrokerQueueCapacity".to_string(),
Value::Number(self.unregister_broker_queue_capacity.into()),
);
json_map.insert(
"supportActingMaster".to_string(),
Value::Bool(self.support_acting_master),
);
json_map.insert(
"enableAllTopicList".to_string(),
Value::Bool(self.enable_all_topic_list),
);
json_map.insert(
"enableTopicList".to_string(),
Value::Bool(self.enable_topic_list),
);
json_map.insert(
"notifyMinBrokerIdChanged".to_string(),
Value::Bool(self.notify_min_broker_id_changed),
);
json_map.insert(
"enableControllerInNamesrv".to_string(),
Value::Bool(self.enable_controller_in_namesrv),
);
json_map.insert(
"needWaitForService".to_string(),
Value::Bool(self.need_wait_for_service),
);
json_map.insert(
"waitSecondsForService".to_string(),
Value::Number(self.wait_seconds_for_service.into()),
);
json_map.insert(
"deleteTopicWithBrokerRegistration".to_string(),
Value::Bool(self.delete_topic_with_broker_registration),
);
json_map.insert(
"configBlackList".to_string(),
Value::String(self.config_black_list.clone()),
);

// Convert the HashMap to a JSON value
match serde_json::to_string_pretty(&json_map) {
Ok(json) => Ok(json),
Err(err) => Err(format!("Failed to serialize NamesrvConfig: {}", err)),
}
}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 1, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify implementation by deriving Serialize trait

The current implementation manually constructs a HashMap for serialization, which is verbose and potentially error-prone. Since the struct already uses serde attributes, we can simplify this significantly by deriving the Serialize trait.

  1. Add Serialize to the derive attributes:
-#[derive(Debug, Clone, Deserialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
 pub struct NamesrvConfig {
  1. Simplify the implementation:
 pub fn get_all_configs_format_string(&self) -> Result<String, String> {
-    let mut json_map = HashMap::new();
-    json_map.insert("rocketmqHome".to_string(), Value::String(self.rocketmq_home.clone()));
-    // ... remove all other manual insertions ...
-    
-    match serde_json::to_string_pretty(&json_map) {
+    match serde_json::to_string_pretty(&self) {
         Ok(json) => Ok(json),
         Err(err) => Err(format!("Failed to serialize NamesrvConfig: {}", err)),
     }
 }

This approach:

  • Reduces code duplication
  • Eliminates potential manual mapping errors
  • Automatically handles new fields added to the struct
  • Maintains consistent serialization with the existing serde attributes

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This will not work unless we replace alias derive with rename. But in case this is done there might be breaking changes, so I am not sure

Copy link
Contributor

Choose a reason for hiding this comment

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

@PanGan21, understood. Thank you for clarifying. Indeed, changing alias to rename in serde attributes might introduce breaking changes. Keeping the current implementation makes sense to preserve backwards compatibility.


✏️ Learnings added
Learnt from: PanGan21
PR: mxsm/rocketmq-rust#1485
File: rocketmq-common/src/common/namesrv/namesrv_config.rs:151-245
Timestamp: 2024-12-01T10:26:22.095Z
Learning: In `NamesrvConfig`, replacing `serde(alias = "...")` with `serde(rename = "...")` could cause breaking changes, so manual serialization is preferred to avoid disrupting existing functionality.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link

codecov bot commented Dec 1, 2024

Codecov Report

Attention: Patch coverage is 90.80460% with 16 lines in your changes missing coverage. Please review.

Project coverage is 22.53%. Comparing base (2e3db91) to head (0111bc9).
Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
...namesrv/src/processor/default_request_processor.rs 0.00% 15 Missing ⚠️
...cketmq-common/src/common/namesrv/namesrv_config.rs 99.37% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1485      +/-   ##
==========================================
+ Coverage   22.34%   22.53%   +0.18%     
==========================================
  Files         450      450              
  Lines       58066    58418     +352     
==========================================
+ Hits        12974    13162     +188     
- Misses      45092    45256     +164     

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

Copy link
Owner

@mxsm mxsm left a comment

Choose a reason for hiding this comment

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

LGTM! thanks for your contribution

@mxsm mxsm merged commit c059ee5 into mxsm:main Dec 1, 2024
17 of 21 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved and removed ready to review waiting-review waiting review this PR labels Dec 1, 2024
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 feature🚀 Suggest an idea for this project. good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature]Namesrv support get namesrv config (request code 319)
4 participants