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 #1813]🚀Implement DefaultMQPushConsumerImpl#ack_async method #1827

Merged
merged 1 commit into from
Dec 17, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Dec 17, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1813

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Introduced acknowledgment message handling functionality.
    • Enhanced methods for processing acknowledgment messages and managing message visibility.
  • Bug Fixes

    • Improved error handling for acknowledgment and message visibility processes.

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

The pull request enhances the DefaultMQPushConsumerImpl in the RocketMQ Rust client, focusing on improving message acknowledgment and visibility management. The changes introduce more robust error handling in the ack_async and change_pop_invisible_time_async methods. The implementation now extracts additional message properties, specifically the PROPERTY_POP_CK, and performs detailed checks when processing acknowledgment messages and changing message invisible time.

Changes

File Change Summary
rocketmq-client/src/consumer/consumer_impl/default_mq_push_consumer_impl.rs - Added import for AckMessageRequestHeader
- Enhanced ack_async method with detailed error handling
- Updated change_pop_invisible_time_async with improved error extraction and validation

Assessment against linked issues

Objective Addressed Explanation
Implement ack_async method [#1813]

Possibly related PRs

Suggested labels

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

Suggested reviewers

  • TeslaRustor
  • RocketmqRustBot
  • SpaceXCN

Poem

🚀 Rocket of code, swift and bright,
Acknowledgments dancing with might,
Error handling, precise and clean,
Messages flow in a rabbit's dream,
RocketMQ's Rust, taking 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-bot
Copy link
Collaborator

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

@rocketmq-rust-robot rocketmq-rust-robot added the feature🚀 Suggest an idea for this project. label Dec 17, 2024
@rocketmq-rust-bot rocketmq-rust-bot added the waiting-review waiting review this PR label Dec 17, 2024
@rocketmq-rust-robot rocketmq-rust-robot added rust Pull requests that update Rust code wip Work In Process labels Dec 17, 2024
@rocketmq-rust-robot rocketmq-rust-robot added this to the v0.4.0 milestone Dec 17, 2024
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: 4

🧹 Nitpick comments (1)
rocketmq-client/src/consumer/consumer_impl/default_mq_push_consumer_impl.rs (1)

1373-1395: Refactor Repeated Error Handling Code

The pattern of checking for an error, logging it, and returning is repeated multiple times (e.g., lines 1379–1382, 1385–1388, 1391–1394). Consider refactoring this repetitive code into a helper function or using the ? operator to simplify error handling, reduce duplication, and enhance readability.

Apply this diff to refactor using the ? operator:

 pub(crate) async fn ack_async(&mut self, message: &MessageExt, consumer_group: &CheetahString) {
     let extra_info = message
         .get_property(&CheetahString::from_static_str(
             MessageConst::PROPERTY_POP_CK,
         ))
         .unwrap_or_default();
-    let extra_info_strs = ExtraInfoUtil::split(extra_info.as_str());
-    if extra_info_strs.is_err() {
-        error!("ackAsync error: {}", extra_info_strs.unwrap_err());
-        return;
-    }
-    let extra_info_strs = extra_info_strs.unwrap();
+    let extra_info_strs = match ExtraInfoUtil::split(extra_info.as_str()) {
+        Ok(value) => value,
+        Err(e) => {
+            error!("ackAsync error: {}", e);
+            return;
+        }
+    };
     let queue_id = ExtraInfoUtil::get_queue_id(extra_info_strs.as_slice());
-    if queue_id.is_err() {
-        error!("ackAsync error: {}", queue_id.unwrap_err());
-        return;
-    }
-    let queue_id = queue_id.unwrap();
+    let queue_id = match queue_id {
+        Ok(value) => value,
+        Err(e) => {
+            error!("ackAsync error: {}", e);
+            return;
+        }
+    };
     let queue_offset = ExtraInfoUtil::get_queue_offset(extra_info_strs.as_slice());
-    if queue_offset.is_err() {
-        error!("ackAsync error: {}", queue_offset.unwrap_err());
-        return;
-    }
-    let queue_offset = queue_offset.unwrap();
+    let queue_offset = match queue_offset {
+        Ok(value) => value,
+        Err(e) => {
+            error!("ackAsync error: {}", e);
+            return;
+        }
+    };

Alternatively, adjust the function to return Result<()> and use the ? operator for error propagation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 996ebdf and 094034a.

📒 Files selected for processing (1)
  • rocketmq-client/src/consumer/consumer_impl/default_mq_push_consumer_impl.rs (2 hunks)
🔇 Additional comments (1)
rocketmq-client/src/consumer/consumer_impl/default_mq_push_consumer_impl.rs (1)

44-44: Import Statement Added

The addition of the AckMessageRequestHeader import is appropriate for the implementation of the acknowledgment functionality.

Comment on lines 1370 to +1452
}

pub(crate) async fn ack_async(&mut self, message: &MessageExt, consumer_group: &CheetahString) {
let extra_info = message
.get_property(&CheetahString::from_static_str(
MessageConst::PROPERTY_POP_CK,
))
.unwrap_or_default();
let extra_info_strs = ExtraInfoUtil::split(extra_info.as_str());
if extra_info_strs.is_err() {
error!("ackAsync error: {}", extra_info_strs.unwrap_err());
return;
}
let extra_info_strs = extra_info_strs.unwrap();
let queue_id = ExtraInfoUtil::get_queue_id(extra_info_strs.as_slice());
if queue_id.is_err() {
error!("ackAsync error: {}", queue_id.unwrap_err());
return;
}
let queue_id = queue_id.unwrap();
let queue_offset = ExtraInfoUtil::get_queue_offset(extra_info_strs.as_slice());
if queue_offset.is_err() {
error!("ackAsync error: {}", queue_offset.unwrap_err());
return;
}
let queue_offset = queue_offset.unwrap();
let broker_name = CheetahString::from(
ExtraInfoUtil::get_broker_name(extra_info_strs.as_slice()).unwrap_or_default(),
);
let topic = message.get_topic();

let client_instance = self.client_instance.as_mut().unwrap();
let des_broker_name = if !broker_name.is_empty()
&& broker_name.starts_with(mix_all::LOGICAL_QUEUE_MOCK_BROKER_PREFIX)
{
let mq = self
.client_config
.queue_with_namespace(MessageQueue::from_parts(
topic,
broker_name.clone(),
queue_id,
));
client_instance
.get_broker_name_from_message_queue(&mq)
.await
} else {
broker_name.clone()
};

let mut find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
if find_broker_result.is_none() {
client_instance
.update_topic_route_info_from_name_server_topic(topic)
.await;
find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
}
if find_broker_result.is_none() {
error!("The broker[{}] not exist", des_broker_name);
return;
}

let request_header = AckMessageRequestHeader {
consumer_group: consumer_group.clone(),
topic: CheetahString::from_string(
ExtraInfoUtil::get_real_topic(extra_info_strs.as_slice(), topic, consumer_group)
.unwrap_or_default(),
),
queue_id,
extra_info,
offset: queue_offset,
topic_request_header: Some(TopicRequestHeader {
rpc_request_header: Some(RpcRequestHeader {
broker_name: Some(broker_name.clone()),
..Default::default()
}),
lo: None,
}),
};
//client_instance.mq_client_api_impl.as_mut().unwrap()
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

Incomplete Implementation of ack_async Function

The ack_async function is currently incomplete, as it ends with unimplemented!("ackAsync");. Please complete the implementation before merging to ensure the acknowledgment process functions correctly.

Comment on lines +1373 to +1451
let extra_info = message
.get_property(&CheetahString::from_static_str(
MessageConst::PROPERTY_POP_CK,
))
.unwrap_or_default();
let extra_info_strs = ExtraInfoUtil::split(extra_info.as_str());
if extra_info_strs.is_err() {
error!("ackAsync error: {}", extra_info_strs.unwrap_err());
return;
}
let extra_info_strs = extra_info_strs.unwrap();
let queue_id = ExtraInfoUtil::get_queue_id(extra_info_strs.as_slice());
if queue_id.is_err() {
error!("ackAsync error: {}", queue_id.unwrap_err());
return;
}
let queue_id = queue_id.unwrap();
let queue_offset = ExtraInfoUtil::get_queue_offset(extra_info_strs.as_slice());
if queue_offset.is_err() {
error!("ackAsync error: {}", queue_offset.unwrap_err());
return;
}
let queue_offset = queue_offset.unwrap();
let broker_name = CheetahString::from(
ExtraInfoUtil::get_broker_name(extra_info_strs.as_slice()).unwrap_or_default(),
);
let topic = message.get_topic();

let client_instance = self.client_instance.as_mut().unwrap();
let des_broker_name = if !broker_name.is_empty()
&& broker_name.starts_with(mix_all::LOGICAL_QUEUE_MOCK_BROKER_PREFIX)
{
let mq = self
.client_config
.queue_with_namespace(MessageQueue::from_parts(
topic,
broker_name.clone(),
queue_id,
));
client_instance
.get_broker_name_from_message_queue(&mq)
.await
} else {
broker_name.clone()
};

let mut find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
if find_broker_result.is_none() {
client_instance
.update_topic_route_info_from_name_server_topic(topic)
.await;
find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
}
if find_broker_result.is_none() {
error!("The broker[{}] not exist", des_broker_name);
return;
}

let request_header = AckMessageRequestHeader {
consumer_group: consumer_group.clone(),
topic: CheetahString::from_string(
ExtraInfoUtil::get_real_topic(extra_info_strs.as_slice(), topic, consumer_group)
.unwrap_or_default(),
),
queue_id,
extra_info,
offset: queue_offset,
topic_request_header: Some(TopicRequestHeader {
rpc_request_header: Some(RpcRequestHeader {
broker_name: Some(broker_name.clone()),
..Default::default()
}),
lo: None,
}),
};
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

Improve Error Handling and Propagate Errors in ack_async

The ack_async function logs errors and returns early upon encountering errors (e.g., lines 1380–1381, 1386–1387, 1392–1393, 1431–1432), but does not inform the caller of these failures. Consider changing the function signature to return Result<()> to propagate errors to the caller, enabling better upstream error handling and reducing silent failures.

);
let topic = message.get_topic();

let client_instance = self.client_instance.as_mut().unwrap();
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

Avoid Potential Panic by Handling Option Properly

Using unwrap() on self.client_instance may lead to a panic if self.client_instance is None. To prevent potential runtime panics, consider handling the None case explicitly or ensuring that self.client_instance is always initialized before invoking this method.

Apply this diff to handle the Option safely:

-let client_instance = self.client_instance.as_mut().unwrap();
+let client_instance = match self.client_instance.as_mut() {
+    Some(instance) => instance,
+    None => {
+        error!("client_instance is None in ack_async");
+        return;
+    }
+};
📝 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 client_instance = self.client_instance.as_mut().unwrap();
let client_instance = match self.client_instance.as_mut() {
Some(instance) => instance,
None => {
error!("client_instance is None in ack_async");
return;
}
};

Comment on lines +1419 to +1433
let mut find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
if find_broker_result.is_none() {
client_instance
.update_topic_route_info_from_name_server_topic(topic)
.await;
find_broker_result = client_instance
.find_broker_address_in_subscribe(&des_broker_name, mix_all::MASTER_ID, true)
.await;
}
if find_broker_result.is_none() {
error!("The broker[{}] not exist", des_broker_name);
return;
}
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

Handle Missing Broker Address Gracefully

In the case where find_broker_result is None after attempting to update the topic route info (lines 1422–1433), the function logs an error and returns without notifying the caller. Consider returning an error to inform the caller about the missing broker, which would enable upstream handling of this situation.

Apply this diff to propagate the error:

 if find_broker_result.is_none() {
     error!("The broker[{}] not exist", des_broker_name);
-    return;
+    return Err(MQClientError::new(format!(
+        "The broker [{}] does not exist",
+        des_broker_name
+    )));
 }

And update the function signature:

-pub(crate) async fn ack_async(&mut self, message: &MessageExt, consumer_group: &CheetahString) {
+pub(crate) async fn ack_async(&mut self, message: &MessageExt, consumer_group: &CheetahString) -> Result<()> {

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

Copy link

codecov bot commented Dec 17, 2024

Codecov Report

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

Project coverage is 28.26%. Comparing base (996ebdf) to head (094034a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...mer/consumer_impl/default_mq_push_consumer_impl.rs 0.00% 76 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1827      +/-   ##
==========================================
- Coverage   28.29%   28.26%   -0.04%     
==========================================
  Files         473      473              
  Lines       65794    65871      +77     
==========================================
  Hits        18617    18617              
- Misses      47177    47254      +77     

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

@rocketmq-rust-bot rocketmq-rust-bot merged commit 0044912 into main Dec 17, 2024
25 of 27 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 17, 2024
@mxsm mxsm deleted the feature-1813 branch December 17, 2024 13:59
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. rust Pull requests that update Rust code wip Work In Process
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀] Implement DefaultMQPushConsumerImpl#ack_async method
3 participants