Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[ISSUE #1809]🍻Implement MQClientAPIImpl#process_pop_response method logic #1810

Merged
merged 1 commit into from
Dec 16, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Dec 16, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1809

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Introduced a new PopResult struct for enhanced message retrieval results.
    • Expanded the process_pop_response method to handle various response scenarios and construct PopResult objects.
  • Bug Fixes

    • Updated numeric types in PopMessageResponseHeader for improved data handling.
  • Tests

    • Added unit tests to validate the Display implementation of PopResult.

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces a new PopResult struct in the RocketMQ client implementation, enhancing message processing capabilities. The changes span across multiple files, including pop_result.rs, mq_client_api_impl.rs, and pop_message_response_header.rs. The modifications focus on improving message retrieval and processing logic, with updates to type definitions, response handling, and introducing new methods for managing message offsets and properties.

Changes

File Change Summary
rocketmq-client/src/consumer/pop_result.rs Added PopResult struct with Default and Clone derive attributes, including fields for message list, pop status, times, and remaining messages. Implemented Display trait for formatted output.
rocketmq-client/src/implementation/mq_client_api_impl.rs Updated process_pop_response method to handle various response codes, decode messages, and construct PopResult. Added build_queue_offset_sorted_map helper function.
rocketmq-remoting/src/protocol/header/pop_message_response_header.rs Updated numeric field types from signed to unsigned (i64u64, i32u32) for pop_time, invisible_time, rest_num, and revive_qid.

Assessment against linked issues

Objective Addressed Explanation
Implement process_pop_response method logic [#1809]

Possibly related PRs

Suggested labels

feature, auto merge, ready to review, waiting-review, AI review first, enhancement

Suggested reviewers

  • TeslaRustor
  • SpaceXCN
  • RocketmqRustBot

Poem

🚀 Popping messages with grace and might,
A struct so clever, it shines so bright!
From queues to results, a journey so neat,
RocketMQ's magic is now complete!
Unsigned and sorted, messages take flight! 🐰


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 16, 2024
@rocketmq-rust-bot
Copy link
Collaborator

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

Copy link

codecov bot commented Dec 16, 2024

Codecov Report

Attention: Patch coverage is 22.88136% with 273 lines in your changes missing coverage. Please review.

Project coverage is 28.30%. Comparing base (31d6100) to head (8d1d914).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...mq-client/src/implementation/mq_client_api_impl.rs 0.00% 272 Missing ⚠️
...src/protocol/header/pop_message_response_header.rs 98.78% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1810      +/-   ##
==========================================
- Coverage   28.42%   28.30%   -0.12%     
==========================================
  Files         472      472              
  Lines       65341    65613     +272     
==========================================
  Hits        18571    18571              
- Misses      46770    47042     +272     

☔ 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

🧹 Nitpick comments (1)
rocketmq-client/src/implementation/mq_client_api_impl.rs (1)

1686-1743: Refactor complex function for improved readability

The build_queue_offset_sorted_map function contains complex logic and nested conditions that make it difficult to read and maintain. Consider refactoring the function by extracting smaller helper functions and adding comments to explain non-trivial logic.

Example refactor:

+fn is_lmq_and_dispatch_needed(message_ext: &MessageExt, topic: &str) -> bool {
+    mix_all::is_lmq(Some(topic)) &&
+        message_ext.reconsume_times() == 0 &&
+        !message_ext.get_property(&CheetahString::from_static_str(
+            MessageConst::PROPERTY_INNER_MULTI_DISPATCH,
+        )).unwrap_or_default().is_empty()
+}
+
fn build_queue_offset_sorted_map(
    topic: &str,
    msg_found_list: &[MessageExt],
) -> HashMap<String, Vec<u64>> {
    let mut sort_map: HashMap<String, Vec<u64>> = HashMap::with_capacity(16);
    for message_ext in msg_found_list {
-       let dispatch = message_ext
-           .get_property(&CheetahString::from_static_str(
-               MessageConst::PROPERTY_INNER_MULTI_DISPATCH,
-           ))
-           .unwrap_or_default();
-       if mix_all::is_lmq(Some(topic))
-           && message_ext.reconsume_times() == 0
-           && !dispatch.is_empty()
-       {
+       if is_lmq_and_dispatch_needed(message_ext, topic) {
            // LMQ processing logic...
        } else {
            // Non-LMQ processing logic...
        }
    }
    sort_map
}

Adding comments and extracting conditions into functions improves clarity.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 31d6100 and 8d1d914.

📒 Files selected for processing (3)
  • rocketmq-client/src/consumer/pop_result.rs (1 hunks)
  • rocketmq-client/src/implementation/mq_client_api_impl.rs (5 hunks)
  • rocketmq-remoting/src/protocol/header/pop_message_response_header.rs (1 hunks)
🔇 Additional comments (2)
rocketmq-client/src/consumer/pop_result.rs (1)

Line range hint 23-37: Implementation of PopResult struct looks good

The PopResult struct is properly defined with the necessary fields and derives Default and Clone, which are appropriate for this use case. The Display implementation provides a clear and formatted string representation of the struct.

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

28-40: Type changes from signed to unsigned integers

The fields pop_time, invisible_time, rest_num, and revive_qid have been changed from signed to unsigned integer types (i64 to u64 and i32 to u32). Ensure that all usages of these fields handle the unsigned types correctly and that negative values are not expected in these contexts.

Confirm that negative values are not possible for these fields and update any related code accordingly.

Comment on lines +1447 to +1685
.unwrap_or_default();
if msg_queue_offset as i64 != offset {
warn!(
"Queue offset[{}] of msg is strange, not equal to the stored \
in msg, {:?}",
msg_queue_offset, message
);
}
let extra_info = ExtraInfoUtil::build_extra_info(
message.queue_offset(),
response_header.pop_time as i64,
response_header.invisible_time as i64,
response_header.revive_qid as i32,
message.get_topic(),
broker_name,
msg_queue_offset as i32,
);
message.put_property(
CheetahString::from_static_str(MessageConst::PROPERTY_POP_CK),
CheetahString::from_string(extra_info),
);
(queue_offset_key, queue_id_key)
} else {
let queue_id_key = ExtraInfoUtil::get_start_offset_info_map_key(
message.get_topic(),
message.queue_id() as i64,
);
let queue_offset_key = ExtraInfoUtil::get_queue_offset_map_key(
message.get_topic(),
message.queue_id() as i64,
message.queue_offset(),
);
let queue_offset = message.queue_offset();
let index = sort_map
.get(&queue_id_key)
.unwrap()
.iter()
.position(|&q| q == queue_offset as u64)
.unwrap_or_default();

let msg_queue_offset = sort_map
.get(&queue_offset_key)
.unwrap()
.get(index)
.cloned()
.unwrap_or_default();
if msg_queue_offset as i64 != queue_offset {
warn!(
"Queue offset[{}] of msg is strange, not equal to the stored \
in msg, {:?}",
msg_queue_offset, message
);
}
let extra_info = ExtraInfoUtil::build_extra_info(
message.queue_offset(),
response_header.pop_time as i64,
response_header.invisible_time as i64,
response_header.revive_qid as i32,
message.get_topic(),
broker_name,
msg_queue_offset as i32,
);
message.put_property(
CheetahString::from_static_str(MessageConst::PROPERTY_POP_CK),
CheetahString::from_string(extra_info),
);
(queue_offset_key, queue_id_key)
};
if is_order && !order_count_info.is_empty() {
let mut count = order_count_info.get(&queue_offset_key);
if count.is_none() {
count = order_count_info.get(&queue_id_key);
}
if let Some(ct) = count {
message.set_reconsume_times(*ct);
}
}
}
}
message.put_property(
CheetahString::from_static_str(MessageConst::PROPERTY_FIRST_POP_TIME),
CheetahString::from(response_header.pop_time.to_string()),
);
message.broker_name = broker_name.clone();
message.set_topic(
NamespaceUtil::without_namespace_with_namespace(
topic.as_str(),
self.client_config
.namespace
.clone()
.unwrap_or_default()
.as_str(),
)
.into(),
)
}
Ok(pop_result)
}
}

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 panics due to unchecked unwrap() calls

In the process_pop_response function, multiple unwrap() calls are used on Option values without prior checks, which can lead to panics if the Option is None. Specifically:

  • Line 1455~: response.get_body_mut().unwrap()
  • Line 1478~: response.decode_command_custom_header::<PopMessageResponseHeader>().unwrap()
  • Lines 1489~ and 1495~: Unwrapping Option fields in response_header without checking.

To enhance the robustness of the code and prevent potential panics, it's recommended to handle Option values safely using pattern matching or the ? operator.

Apply this diff to handle potential None values safely:

- let messages = MessageDecoder::decodes_batch(
-     response.get_body_mut().unwrap(),
-     self.client_config.decode_read_body,
-     self.client_config.decode_decompress_body,
- );
+ let body = response.get_body_mut().ok_or_else(|| {
+     RemotingError("Response body is missing")
+ })?;
+ let messages = MessageDecoder::decodes_batch(
+     body,
+     self.client_config.decode_read_body,
+     self.client_config.decode_decompress_body,
+ );

...

- let response_header = response
-     .decode_command_custom_header::<PopMessageResponseHeader>()
-     .unwrap();
+ let response_header = response
+     .decode_command_custom_header::<PopMessageResponseHeader>()
+     .map_err(|_| RemotingError("Failed to decode PopMessageResponseHeader"))?;

...

- let start_offset_info = ExtraInfoUtil::parse_start_offset_info(
-     response_header.start_offset_info.as_ref().unwrap_or(&CheetahString::from_slice("")),
- ).map_err(RemotingError)?;
+ let start_offset_str = response_header.start_offset_info.as_deref().unwrap_or("");
+ let start_offset_info = ExtraInfoUtil::parse_start_offset_info(start_offset_str)
+     .map_err(RemotingError)?;

Repeat similar safe handling for other instances where unwrap() is called.

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

@rocketmq-rust-bot rocketmq-rust-bot merged commit f3000f5 into main Dec 16, 2024
23 of 25 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 16, 2024
@mxsm mxsm deleted the feature-1809 branch December 17, 2024 13:59
# for free to join this conversation on GitHub. Already have an account? # 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🚀] Implement MQClientAPIImpl#process_pop_response method logic
4 participants