Skip to content

[ISSUE #1763]🚀Implement ConsumerOrderInfoManager#auto_clean method function🔥 #1765

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
Dec 14, 2024

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Dec 14, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1763

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Enhanced type specificity for consumer order management.
    • Introduced a cleanup method for stale consumer order information.
    • Added a custom string representation for TopicConfig.
  • Bug Fixes

    • Improved cloning behavior for BrokerRuntime.
  • Documentation

    • Updated visibility for subscription_group_wrapper and SubscriptionGroupWrapper to enhance accessibility.
  • Refactor

    • Modified struct definitions to accommodate generics for improved flexibility.

@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 Difficulty level/Moderate Moderate difficult ISSUE feature🚀 Suggest an idea for this project. rust Pull requests that update Rust code labels Dec 14, 2024
Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

Walkthrough

The pull request introduces several modifications to the rocketmq-broker and rocketmq-common codebase, focusing on enhancing type specificity and flexibility within the BrokerRuntime, ConsumerOrderInfoManager, and ChangeInvisibleTimeProcessor structs. Key changes include the parameterization of ConsumerOrderInfoManager and its methods, updates to the ChangeInvisibleTimeProcessor to accommodate the new type, and improved public access to certain fields in the SubscriptionGroupManager. Additionally, a new Display implementation for TopicConfig is added for better string representation.

Changes

File Path Change Summary
rocketmq-broker/src/broker_runtime.rs Updated consumer_order_info_manager type to Arc<ConsumerOrderInfoManager<DefaultMessageStore>> and adjusted initialization. Updated Clone implementation.
rocketmq-broker/src/offset/manager/consumer_order_info_manager.rs Made ConsumerOrderInfoManager generic with type parameter MS. Added fields and methods, including auto_clean and Display implementation for OrderInfo.
rocketmq-broker/src/processor/change_invisible_time_processor.rs Updated consumer_order_info_manager type to Arc<ConsumerOrderInfoManager<MS>>. Adjusted constructor method accordingly.
rocketmq-broker/src/subscription/manager/subscription_group_manager.rs Changed visibility of subscription_group_wrapper and SubscriptionGroupWrapper to public. Added getter method for subscription_group_wrapper.
rocketmq-common/src/common/config.rs Added Display implementation for TopicConfig for better string representation.

Assessment against linked issues

Objective Addressed Explanation
Implement ConsumerOrderInfoManager#auto_clean method (1763)

Possibly related PRs

Suggested reviewers

  • TeslaRustor
  • SpaceXCN

Poem

🐰 In the code where rabbits play,
Types get clearer every day.
Order info now shines bright,
With clean methods, pure delight!
So hop along, let’s celebrate,
For better code, we can’t wait! 🎉

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


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.

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

🧹 Outside diff range and nitpick comments (6)
rocketmq-broker/src/offset/manager/consumer_order_info_manager.rs (2)

Line range hint 212-220: Implement or remove the update_lock_free_timestamp method

The method update_lock_free_timestamp is currently unimplemented. If it's required for the functionality, please provide an appropriate implementation. If not, consider removing it to avoid confusion.

Would you like assistance in implementing this method or creating a GitHub issue to track it?


277-295: Ensure consistency in the Display implementation for OrderInfo

The Display implementation for OrderInfo uses both field names and values. To enhance readability and maintain consistency, consider formatting the struct output more succinctly or using debug formatting if detailed output is required.

Optionally, you can simplify the implementation:

- write!(
-     f,
-     "OrderInfo {{ popTime: {}, invisibleTime: {:?}, offsetList: {:?}, \
-      offsetNextVisibleTime: {:?}, offsetConsumedCount: {:?}, lastConsumeTimestamp: {}, \
-      commitOffsetBit: {}, attemptId: {} }}",
-     self.pop_time,
-     self.invisible_time,
-     self.offset_list,
-     self.offset_next_visible_time,
-     self.offset_consumed_count,
-     self.last_consume_timestamp,
-     self.commit_offset_bit,
-     self.attempt_id
- )
+ write!(f, "{:?}", self)

This leverages the Debug implementation for a concise representation.

rocketmq-broker/src/subscription/manager/subscription_group_manager.rs (2)

41-41: Re-evaluate the visibility change of subscription_group_wrapper

The field subscription_group_wrapper has been made public (pub(crate)). Exposing internal mutex-protected data can lead to unintended side effects or race conditions if not managed carefully. Consider providing controlled access through methods instead of making the field public.

If external access is necessary, ensure that appropriate getter methods are used to maintain encapsulation.


59-61: Redundant method due to field visibility

The method subscription_group_wrapper() returns a reference to the now-public subscription_group_wrapper field. Since the field is already public, this method may be redundant.

Consider removing the method or keeping the field private to enforce controlled access.

- pub(crate) subscription_group_wrapper: Arc<parking_lot::Mutex<SubscriptionGroupWrapper>>,
+ subscription_group_wrapper: Arc<parking_lot::Mutex<SubscriptionGroupWrapper>>,

...

- pub fn subscription_group_wrapper(&self) -> &Arc<parking_lot::Mutex<SubscriptionGroupWrapper>> {
-     &self.subscription_group_wrapper
- }
rocketmq-common/src/common/config.rs (1)

43-59: Enhance the Display implementation for TopicConfig

The current Display implementation manually formats each field, which can be error-prone and hard to maintain. Consider using the {:#?} formatter for a cleaner and more maintainable output or deriving Display using procedural macros if available.

Alternatively, if detailed custom formatting is necessary, ensure all fields are correctly formatted.

- impl Display for TopicConfig {
-     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-         write!(
-             f,
-             "TopicConfig {{ topic_name: {:?}, read_queue_nums: {}, write_queue_nums: {}, perm: \
-              {}, topic_filter_type: {}, topic_sys_flag: {}, order: {}, attributes: {:?} }}",
-             self.topic_name,
-             self.read_queue_nums,
-             self.write_queue_nums,
-             self.perm,
-             self.topic_filter_type,
-             self.topic_sys_flag,
-             self.order,
-             self.attributes
-         )
-     }
- }
+ impl std::fmt::Display for TopicConfig {
+     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+         write!(f, "{:?}", self)
+     }
+ }

This simplifies maintenance and ensures consistency.

rocketmq-broker/src/broker_runtime.rs (1)

244-250: Consider adding error handling for initialization failures.

While the initialization provides all required dependencies, it might be good to add error handling for potential initialization failures. Consider using Result to handle cases where the initialization might fail.

Example approach:

-let subscription_group_manager =
-    Arc::new(SubscriptionGroupManager::new(broker_config.clone(), None));
-let consumer_order_info_manager = Arc::new(ConsumerOrderInfoManager::new(
-    broker_config.clone(),
-    Arc::new(topic_config_manager.clone()),
-    subscription_group_manager.clone(),
-));
+let subscription_group_manager = SubscriptionGroupManager::new(broker_config.clone(), None)
+    .map(Arc::new)
+    .map_err(|e| format!("Failed to initialize SubscriptionGroupManager: {}", e))?;
+let consumer_order_info_manager = ConsumerOrderInfoManager::new(
+    broker_config.clone(),
+    Arc::new(topic_config_manager.clone()),
+    subscription_group_manager.clone(),
+)
+    .map(Arc::new)
+    .map_err(|e| format!("Failed to initialize ConsumerOrderInfoManager: {}", e))?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b419985 and 13eae18.

📒 Files selected for processing (5)
  • rocketmq-broker/src/broker_runtime.rs (3 hunks)
  • rocketmq-broker/src/offset/manager/consumer_order_info_manager.rs (4 hunks)
  • rocketmq-broker/src/processor/change_invisible_time_processor.rs (2 hunks)
  • rocketmq-broker/src/subscription/manager/subscription_group_manager.rs (3 hunks)
  • rocketmq-common/src/common/config.rs (2 hunks)
🔇 Additional comments (4)
rocketmq-broker/src/subscription/manager/subscription_group_manager.rs (1)

206-206: Verify the necessity of making SubscriptionGroupWrapper public

The struct SubscriptionGroupWrapper is now public (pub(crate)). Assess if this exposure is required for functionality. If not, keeping it private helps maintain encapsulation and reduces potential misuse.

Please confirm if external modules need direct access to SubscriptionGroupWrapper.

rocketmq-broker/src/broker_runtime.rs (3)

106-106: LGTM: Type parameterization improves type safety.

The change to use Arc<ConsumerOrderInfoManager<DefaultMessageStore>> makes the relationship between the manager and store type explicit, preventing potential type mismatches at compile time.


157-157: LGTM: Clone implementation correctly handles the parameterized type.

The Clone trait implementation properly maintains the Arc wrapper while handling the parameterized ConsumerOrderInfoManager type.


258-258: LGTM: Field assignments maintain proper dependency order.

The field assignments are correctly ordered to ensure all dependencies are available, and the types are consistent with the struct definition.

Also applies to: 260-260

Comment on lines +161 to +163
for (queue_id, order_info) in qs.iter_mut() {
if *queue_id == topic_config.read_queue_nums as i32 {
queues_to_remove.push(*queue_id);
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

Correct the queue ID validation condition

The condition if *queue_id == topic_config.read_queue_nums as i32 may not correctly identify non-existent queues. Since queue IDs range from 0 to read_queue_nums - 1, the condition should check for queue IDs greater than or equal to read_queue_nums.

Apply this diff to fix the off-by-one error:

- if *queue_id == topic_config.read_queue_nums as i32 {
+ if *queue_id >= topic_config.read_queue_nums as i32 {
📝 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
for (queue_id, order_info) in qs.iter_mut() {
if *queue_id == topic_config.read_queue_nums as i32 {
queues_to_remove.push(*queue_id);
for (queue_id, order_info) in qs.iter_mut() {
if *queue_id >= topic_config.read_queue_nums as i32 {
queues_to_remove.push(*queue_id);

@@ -59,7 +59,7 @@ pub struct ChangeInvisibleTimeProcessor<MS> {
topic_config_manager: TopicConfigManager,
message_store: ArcMut<MS>,
consumer_offset_manager: Arc<ConsumerOffsetManager>,
consumer_order_info_manager: Arc<ConsumerOrderInfoManager>,
consumer_order_info_manager: Arc<ConsumerOrderInfoManager<MS>>,
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

Type parameter MS missing trait bounds

The generic type MS is used in ChangeInvisibleTimeProcessor<MS> but lacks trait bounds. This may lead to compilation issues if MS needs to implement certain traits.

Ensure that MS has the necessary trait bounds, such as MessageStore, where required in the implementation.

- pub struct ChangeInvisibleTimeProcessor<MS> {
+ pub struct ChangeInvisibleTimeProcessor<MS: MessageStore> {

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

@@ -74,7 +74,7 @@
topic_config_manager: TopicConfigManager,
message_store: ArcMut<MS>,
consumer_offset_manager: Arc<ConsumerOffsetManager>,
consumer_order_info_manager: Arc<ConsumerOrderInfoManager>,
consumer_order_info_manager: Arc<ConsumerOrderInfoManager<MS>>,
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

Update the constructor to reflect trait bounds on MS

Similarly, ensure that the new method reflects the trait bounds of MS if it's required for the functionality.

Adjust the implementation to include the trait bounds.

- impl<MS> ChangeInvisibleTimeProcessor<MS> {
+ impl<MS: MessageStore> ChangeInvisibleTimeProcessor<MS> {

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

@rocketmq-rust-bot rocketmq-rust-bot merged commit a9067d9 into main Dec 14, 2024
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 14, 2024
Copy link

codecov bot commented Dec 14, 2024

Codecov Report

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

Project coverage is 28.18%. Comparing base (b419985) to head (13eae18).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
.../src/offset/manager/consumer_order_info_manager.rs 0.00% 95 Missing ⚠️
rocketmq-common/src/common/config.rs 0.00% 15 Missing ⚠️
rocketmq-broker/src/broker_runtime.rs 0.00% 10 Missing ⚠️
...subscription/manager/subscription_group_manager.rs 0.00% 3 Missing ⚠️
...r/src/processor/change_invisible_time_processor.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1765      +/-   ##
==========================================
- Coverage   28.23%   28.18%   -0.06%     
==========================================
  Files         467      467              
  Lines       64684    64800     +116     
==========================================
  Hits        18265    18265              
- Misses      46419    46535     +116     

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

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 Difficulty level/Moderate Moderate difficult ISSUE feature🚀 Suggest an idea for this project. rust Pull requests that update Rust code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀]Implement ConsumerOrderInfoManager#auto_clean method function
3 participants