Skip to content

[ISSUE #703]🚀Implement RpcClientUtils#encode_body method🚀#707

Merged
mxsm merged 2 commits intomainfrom
feature-703-1
Jun 28, 2024
Merged

[ISSUE #703]🚀Implement RpcClientUtils#encode_body method🚀#707
mxsm merged 2 commits intomainfrom
feature-703-1

Conversation

@mxsm
Copy link
Copy Markdown
Owner

@mxsm mxsm commented Jun 28, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #703

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Introduced SerdeJsonUtils for improved JSON handling and deserialization across multiple components.
  • Refactor

    • Removed RemotingSerializable implementation from various structs to streamline serialization and deserialization process.
    • Updated serialization logic to use SerdeJsonUtils for enhanced performance and consistency.
  • Bug Fixes

    • Fixed inconsistent serialization behavior by standardizing on SerdeJsonUtils.
  • Chores

    • Cleaned up dependency imports and removed unused trait implementations to improve code clarity and maintainability.

@github-actions github-actions bot requested review from SpaceXCN and TeslaRustor June 28, 2024 13:07
@mxsm
Copy link
Copy Markdown
Owner Author

mxsm commented Jun 28, 2024

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 28, 2024

Walkthrough

The recent changes replace existing JSON serialization code with a new utility, SerdeJsonUtils. The implementation of the RemotingSerializable trait is extensively removed across various modules, where SerdeJsonUtils now handles JSON encoding and decoding. Additionally, the encode_body function in RpcClientUtils has been updated to accommodate different types of body inputs more explicitly.

Changes

File(s) Change Summary
rocketmq-broker/src/.../consumer_offset_manager.rs, rocketmq-broker/src/.../subscription_group_manager.rs, rocketmq-namesrv/src/kvconfig.rs, rocketmq-remoting/src/protocol/.../*.rs Removed RemotingSerializable implementations for various structs.
rocketmq-broker/src/out_api/broker_outer_api.rs, rocketmq-broker/src/processor/client_manage_processor.rs, rocketmq-namesrv/src/kvconfig/kvconfig_mananger.rs, rocketmq-namesrv/src/processor/default_request_processor.rs Replaced decoding functions with SerdeJsonUtils.
rocketmq-common/src/utils.rs Added new module serde_json_utils.
rocketmq-common/src/utils/serde_json_utils.rs Added a public decode function to SerdeJsonUtils.
rocketmq-remoting/src/protocol.rs Refactored serialization with SerdeJsonUtils and introduced a new JsonSerializable trait.
rocketmq-remoting/src/rpc/rpc_client_utils.rs Updated encode_body function to handle different input types and added necessary imports.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant API as BrokerOuterAPI
    participant Serde as SerdeJsonUtils
    participant Broker as RocketMQ Broker

    Client ->> API: Send Request with Body
    API ->> Serde: Decode Body
    Serde -->> API: Decoded KVTable
    API ->> Broker: Process Request
    Broker ->> API: Send Response
    API -->> Client: Response
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement RpcClientUtils#encode_body method (#703)

Poem

In fields where rockets fly and code does flow,
A bunny hops through updates, making everything glow.
With JSON to parse and requests to encode,
A rabbit brings enhancements, lightening the load.
So cheer to the code and the bunny so bright,
For RocketMQ glows even better tonight.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@mxsm
Copy link
Copy Markdown
Owner Author

mxsm commented Jun 28, 2024

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

@SpaceXCN SpaceXCN added approved PR has approved and removed ready to review labels Jun 28, 2024
@codecov
Copy link
Copy Markdown

codecov bot commented Jun 28, 2024

Codecov Report

Attention: Patch coverage is 28.20513% with 28 lines in your changes missing coverage. Please review.

Project coverage is 27.23%. Comparing base (01cd6f7) to head (65b6eef).

Files Patch % Lines
rocketmq-remoting/src/rpc/rpc_client_utils.rs 0.00% 11 Missing ⚠️
...namesrv/src/processor/default_request_processor.rs 0.00% 5 Missing ⚠️
...mq-broker/src/processor/client_manage_processor.rs 0.00% 3 Missing ⚠️
rocketmq-remoting/src/protocol.rs 66.66% 2 Missing ⚠️
...ge_operation_header/send_message_request_header.rs 0.00% 2 Missing ⚠️
rocketmq-broker/src/out_api/broker_outer_api.rs 0.00% 1 Missing ⚠️
rocketmq-namesrv/src/kvconfig/kvconfig_mananger.rs 0.00% 1 Missing ⚠️
.../protocol/body/broker_body/register_broker_body.rs 0.00% 1 Missing ⚠️
...e_operation_header/send_message_response_header.rs 0.00% 1 Missing ⚠️
...rc/protocol/header/pull_message_response_header.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #707      +/-   ##
==========================================
+ Coverage   26.90%   27.23%   +0.33%     
==========================================
  Files         261      262       +1     
  Lines       20426    20536     +110     
==========================================
+ Hits         5495     5594      +99     
- Misses      14931    14942      +11     

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

@mxsm mxsm merged commit 29a2345 into main Jun 28, 2024
@mxsm mxsm deleted the feature-703-1 branch June 28, 2024 15:00
Copy link
Copy Markdown
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: 4

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 01cd6f7 and 65b6eef.

Files selected for processing (25)
  • rocketmq-broker/src/offset/manager/consumer_offset_manager.rs (1 hunks)
  • rocketmq-broker/src/out_api/broker_outer_api.rs (2 hunks)
  • rocketmq-broker/src/processor/client_manage_processor.rs (2 hunks)
  • rocketmq-broker/src/subscription/manager/subscription_group_manager.rs (1 hunks)
  • rocketmq-common/src/utils.rs (1 hunks)
  • rocketmq-common/src/utils/serde_json_utils.rs (1 hunks)
  • rocketmq-namesrv/src/kvconfig.rs (2 hunks)
  • rocketmq-namesrv/src/kvconfig/kvconfig_mananger.rs (2 hunks)
  • rocketmq-namesrv/src/processor/default_request_processor.rs (4 hunks)
  • rocketmq-remoting/src/protocol.rs (3 hunks)
  • rocketmq-remoting/src/protocol/body/broker_body/broker_member_group.rs (2 hunks)
  • rocketmq-remoting/src/protocol/body/broker_body/cluster_info.rs (2 hunks)
  • rocketmq-remoting/src/protocol/body/broker_body/register_broker_body.rs (2 hunks)
  • rocketmq-remoting/src/protocol/body/get_consumer_listby_group_response_body.rs (1 hunks)
  • rocketmq-remoting/src/protocol/body/kv_table.rs (1 hunks)
  • rocketmq-remoting/src/protocol/body/topic/topic_list.rs (1 hunks)
  • rocketmq-remoting/src/protocol/body/topic_info_wrapper.rs (2 hunks)
  • rocketmq-remoting/src/protocol/body/topic_info_wrapper/topic_config_wrapper.rs (2 hunks)
  • rocketmq-remoting/src/protocol/body/topic_info_wrapper/topic_queue_wrapper.rs (1 hunks)
  • rocketmq-remoting/src/protocol/header/message_operation_header/send_message_request_header.rs (3 hunks)
  • rocketmq-remoting/src/protocol/header/message_operation_header/send_message_response_header.rs (1 hunks)
  • rocketmq-remoting/src/protocol/header/pull_message_response_header.rs (1 hunks)
  • rocketmq-remoting/src/protocol/heartbeat/heartbeat_data.rs (5 hunks)
  • rocketmq-remoting/src/protocol/route/route_data_view.rs (2 hunks)
  • rocketmq-remoting/src/rpc/rpc_client_utils.rs (2 hunks)
Files not reviewed due to errors (1)
  • rocketmq-remoting/src/protocol/body/topic_info_wrapper/topic_queue_wrapper.rs (no review received)
Files skipped from review due to trivial changes (6)
  • rocketmq-common/src/utils.rs
  • rocketmq-remoting/src/protocol/body/get_consumer_listby_group_response_body.rs
  • rocketmq-remoting/src/protocol/body/kv_table.rs
  • rocketmq-remoting/src/protocol/body/topic/topic_list.rs
  • rocketmq-remoting/src/protocol/body/topic_info_wrapper.rs
  • rocketmq-remoting/src/protocol/header/message_operation_header/send_message_response_header.rs
Additional comments not posted (13)
rocketmq-remoting/src/rpc/rpc_client_utils.rs (2)

21-21: Addition of BytesMut import.

This import is necessary for the changes in the encode_body function, which now handles BytesMut explicitly.


24-24: Addition of RemotingSerializable import.

This import is crucial for the changes in encode_body, allowing the function to check if the body implements the RemotingSerializable interface.

rocketmq-remoting/src/protocol/heartbeat/heartbeat_data.rs (2)

43-43: Import of SerdeJsonUtils and RemotingSerializable.

These imports are necessary for the unit tests to utilize the new serialization utility, aligning with the changes in serialization strategy across the project.

Also applies to: 46-46


64-64: Use of SerdeJsonUtils in tests.

The tests correctly use SerdeJsonUtils for deserialization, ensuring that the HeartbeatData struct is properly handled. This change is consistent with the overall move towards using SerdeJsonUtils across the project.

Also applies to: 80-80, 96-96

rocketmq-remoting/src/protocol/header/pull_message_response_header.rs (1)

27-27: Removal of RemotingSerializable trait from PullMessageResponseHeader.

This change is part of the broader refactoring to use SerdeJsonUtils for serialization. Ensure that all usages of PullMessageResponseHeader are updated to reflect this change.

Verification successful

Removal of RemotingSerializable trait from PullMessageResponseHeader verified.

The PullMessageResponseHeader struct now uses serde::Serialize and serde::Deserialize for serialization, confirming the transition to SerdeJsonUtils. All relevant usages have been updated accordingly.

  • rocketmq-remoting/src/protocol/header/pull_message_response_header.rs
  • rocketmq-broker/src/processor/pull_message_processor.rs
  • rocketmq-broker/src/processor/default_pull_message_result_handler.rs
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all usages of `PullMessageResponseHeader` are updated.
rg --type rust --glob '*.rs' 'PullMessageResponseHeader'

Length of output: 1401



Script:

#!/bin/bash
# Description: Check for references to `RemotingSerializable` and ensure `SerdeJsonUtils` is used in relevant files.

# Check for references to `RemotingSerializable` in the relevant files
echo "Checking for references to RemotingSerializable..."
rg --type rust --glob '*.rs' 'RemotingSerializable' rocketmq-remoting/src/protocol/header/pull_message_response_header.rs rocketmq-broker/src/processor/pull_message_processor.rs rocketmq-broker/src/processor/default_pull_message_result_handler.rs

# Check for usage of `SerdeJsonUtils` in the relevant files
echo "Checking for usage of SerdeJsonUtils..."
rg --type rust --glob '*.rs' 'SerdeJsonUtils' rocketmq-remoting/src/protocol/header/pull_message_response_header.rs rocketmq-broker/src/processor/pull_message_processor.rs rocketmq-broker/src/processor/default_pull_message_result_handler.rs

Length of output: 687



Script:

#!/bin/bash
# Description: Check for common serialization and deserialization functions or traits in the relevant files.

# Check for common serialization and deserialization functions or traits
echo "Checking for common serialization and deserialization functions or traits..."
rg --type rust --glob '*.rs' 'Serialize|Deserialize|to_string|from_str|json' rocketmq-remoting/src/protocol/header/pull_message_response_header.rs rocketmq-broker/src/processor/pull_message_processor.rs rocketmq-broker/src/processor/default_pull_message_result_handler.rs

Length of output: 2299

rocketmq-remoting/src/protocol/header/message_operation_header/send_message_request_header.rs (2)

26-26: Refactoring of serialization traits approved.

The removal of RemotingSerializable aligns with the broader refactoring to use SerdeJsonUtils for JSON serialization. Ensure that all serialization and deserialization points in the codebase are updated accordingly.


147-147: Consistency in header refactoring noted.

The changes are consistent across different headers, removing RemotingSerializable in favor of using SerdeJsonUtils. This should simplify the serialization process and reduce dependency on custom serialization traits.

rocketmq-broker/src/out_api/broker_outer_api.rs (1)

213-213: Refactoring to use SerdeJsonUtils for decoding approved.

The switch to SerdeJsonUtils::decode for the KVTable in the register_broker method is a part of the broader initiative to standardize JSON serialization/deserialization. Ensure that SerdeJsonUtils is thoroughly tested to handle all expected types.

rocketmq-namesrv/src/processor/default_request_processor.rs (3)

180-182: Use of SerdeJsonUtils for DataVersion decoding approved.

The refactoring to use SerdeJsonUtils::decode for DataVersion in the query_broker_topic_config method aligns with the new serialization strategy. Ensure that DataVersion is correctly implemented to be serializable and deserializable with SerdeJsonUtils.


412-412: Decoding TopicRouteData using SerdeJsonUtils is consistent with project standards.

The use of SerdeJsonUtils::decode in register_topic_to_name_srv ensures consistency in handling JSON data across the application. Verify that TopicRouteData includes all necessary fields for correct operation.


519-521: Decoding of TopicConfigAndMappingSerializeWrapper using SerdeJsonUtils is correct.

This change is part of the ongoing refactoring to standardize JSON operations. Ensure that TopicConfigAndMappingSerializeWrapper is fully compatible with SerdeJsonUtils for correct functionality.

rocketmq-remoting/src/protocol.rs (2)

27-27: Inclusion of SerdeJsonUtils in protocol module approved.

The addition of SerdeJsonUtils to the protocol module facilitates centralized JSON handling, which is crucial for maintaining consistency across different parts of the application.


325-328: Enhancements to RemotingSerializable and introduction of JsonSerializable approved.

The updates to RemotingSerializable and the new JsonSerializable trait align with the project's efforts to standardize JSON operations. Ensure that all serializable types implement these traits correctly to maintain functionality.

Also applies to: 330-342

Comment on lines +22 to +27
pub fn decode<T>(bytes: &[u8]) -> T
where
T: serde::de::DeserializeOwned,
{
serde_json::from_slice::<T>(bytes).unwrap()
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Potential panic risk in decode function.

The decode function uses unwrap which may cause the application to panic if deserialization fails. Consider handling this error more gracefully to improve robustness.

- serde_json::from_slice::<T>(bytes).unwrap()
+ serde_json::from_slice::<T>(bytes).map_err(SerdeJsonError::JsonError)

Committable suggestion was skipped due to low confidence.

Comment on lines +52 to +65
pub fn encode_body(body: &dyn Any) -> Option<Bytes> {
if body.is::<()>() {
None
} else if let Some(bytes) = body.downcast_ref::<Bytes>() {
Some(bytes.clone())
} else if let Some(remoting_serializable) = body.downcast_ref::<&dyn RemotingSerializable>()
{
Some(Bytes::from(remoting_serializable.encode()))
} else if let Some(buffer) = body.downcast_ref::<BytesMut>() {
let data = buffer.clone().freeze();
Some(data)
} else {
None
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Refactor encode_body to handle multiple body types.

The refactored encode_body function now explicitly handles different types of bodies ((), Bytes, RemotingSerializable, BytesMut). This change increases the flexibility and robustness of the method. However, ensure that all possible types that can be passed to this function are accounted for, and consider adding a default case or logging for unhandled types.

+ else {
+     log::warn("Unhandled body type: {:?}", body.type_id());
+     None
+ }
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
pub fn encode_body(body: &dyn Any) -> Option<Bytes> {
if body.is::<()>() {
None
} else if let Some(bytes) = body.downcast_ref::<Bytes>() {
Some(bytes.clone())
} else if let Some(remoting_serializable) = body.downcast_ref::<&dyn RemotingSerializable>()
{
Some(Bytes::from(remoting_serializable.encode()))
} else if let Some(buffer) = body.downcast_ref::<BytesMut>() {
let data = buffer.clone().freeze();
Some(data)
} else {
None
}
pub fn encode_body(body: &dyn Any) -> Option<Bytes> {
if body.is::<()>() {
None
} else if let Some(bytes) = body.downcast_ref::<Bytes>() {
Some(bytes.clone())
} else if let Some(remoting_serializable) = body.downcast_ref::<&dyn RemotingSerializable>()
{
Some(Bytes::from(remoting_serializable.encode()))
} else if let Some(buffer) = body.downcast_ref::<BytesMut>() {
let data = buffer.clone().freeze();
Some(data)
} else {
log::warn("Unhandled body type: {:?}", body.type_id());
None
}

let result = FileUtils::file_to_string(self.namesrv_config.kv_config_path.as_str());
if let Ok(content) = result {
let wrapper = KVConfigSerializeWrapper::decode(content.as_bytes());
let wrapper = SerdeJsonUtils::decode::<KVConfigSerializeWrapper>(content.as_bytes());
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Refactored deserialization in load method.

The use of SerdeJsonUtils::decode is a good replacement for the previous method. However, consider handling potential errors from decode to prevent runtime panics.

- let wrapper = KVConfigSerializeWrapper::decode(content.as_bytes());
+ let wrapper = SerdeJsonUtils::decode::<KVConfigSerializeWrapper>(content.as_bytes()).unwrap_or_default();
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
let wrapper = SerdeJsonUtils::decode::<KVConfigSerializeWrapper>(content.as_bytes());
let wrapper = SerdeJsonUtils::decode::<KVConfigSerializeWrapper>(content.as_bytes()).unwrap_or_default();

Comment on lines +132 to +134
let heartbeat_data = SerdeJsonUtils::decode::<HeartbeatData>(
request.body().as_ref().map(|v| v.as_ref()).unwrap(),
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Refactored deserialization in heart_beat method.

The use of SerdeJsonUtils::decode is a good replacement for the previous method. However, consider handling potential errors from decode to prevent runtime panics.

- let heartbeat_data = HeartbeatData::decode(request.body().as_ref());
+ let heartbeat_data = SerdeJsonUtils::decode::<HeartbeatData>(request.body().as_ref().map(|v| v.as_ref()).unwrap()).unwrap_or_default();
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
let heartbeat_data = SerdeJsonUtils::decode::<HeartbeatData>(
request.body().as_ref().map(|v| v.as_ref()).unwrap(),
);
let heartbeat_data = SerdeJsonUtils::decode::<HeartbeatData>(
request.body().as_ref().map(|v| v.as_ref()).unwrap(),
).unwrap_or_default();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved PR has approved auto merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Implement RpcClientUtils#encode_body method

2 participants