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 #2554]🚀Fix pop consumer can't start🔥 #2555

Merged
merged 1 commit into from
Feb 15, 2025
Merged

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Feb 15, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #2554

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features
    • Administration now supports explicit group configuration for more tailored setup.
    • The consumer now automatically assigns a default nameserver address for improved connectivity.
    • New interfaces allow flexible access to client configuration settings.

Copy link
Contributor

coderabbitai bot commented Feb 15, 2025

Walkthrough

The changes update the administration configuration across multiple modules. In the RocketMQ client and tools, the initialization of the admin_ext_group has been modified: the constructor now requires a CheetahString parameter instead of using a default value, and a local variable derived from a static string is now used consistently. Additionally, the RocketMQ example for consumers has been updated to explicitly set the namesrv_addr using a static default value. Inline accessor methods for client configuration have also been introduced in the tools module.

Changes

File(s) Change Summary
rocketmq-client/src/admin/default_mq_admin_ext_impl.rs
rocketmq-tools/src/admin/default_mq_admin_ext.rs
Updated admin extension initialization: The constructor now accepts a CheetahString admin_ext_group parameter and initializes the field directly. In the tools module, a local variable is used for this initialization and two new inline methods, client_config and client_config_mut, are added.
rocketmq-example/.../pop_consumer.rs Modified switch_pop_consumer to update the namesrv_addr in the client configuration by wrapping the static DEFAULT_NAMESRVADDR into a CheetahString.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Admin as DefaultMQAdminExtImpl
    App->>Admin: Call new(rpc_hook, timeout, client_config, admin_ext_group)
    Admin-->>App: Return instance with admin_ext_group configured
Loading
sequenceDiagram
    participant Consumer as PopConsumer
    participant Config as ClientConfig
    Consumer->>Config: Retrieve mutable config via client_config_mut()
    Config-->>Consumer: Provide mutable client configuration
    Consumer->>Config: Set namesrv_addr to DEFAULT_NAMESRVADDR (as CheetahString)
    Consumer-->>Consumer: Proceed with consumer switch logic
Loading

Possibly related PRs

Suggested labels

bug🐛, approved, auto merge, AI review first, rocketmq-tools crate

Suggested reviewers

  • TeslaRustor
  • SpaceXCN
  • rocketmq-rust-bot

Poem

Hop, hop, through the code I bound,
Admin extensions now neatly found.
With a tweak and a parameter so bright,
Configuration flows just right.
A joyful hop on lines of change,
Celebrated in code by this rabbit strange!


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🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

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

🔭 Outside diff range comments (2)
rocketmq-example/examples/consumer/pop_consumer.rs (2)

63-94: ⚠️ Potential issue

Improve error handling in switch_pop_consumer function.

The function uses multiple unwrap() calls which could lead to runtime panics. Consider proper error handling using the ? operator or explicit error handling.

Apply this diff to improve error handling:

async fn switch_pop_consumer() -> Result<()> {
    let mut mq_admin_ext = DefaultMQAdminExt::new();
    mq_admin_ext.client_config_mut().namesrv_addr =
        Some(CheetahString::from_static_str(DEFAULT_NAMESRVADDR));
-   MQAdminExt::start(&mut mq_admin_ext).await.unwrap();
-   let broker_datas =
-       MQAdminExt::examine_topic_route_info(&mq_admin_ext, CheetahString::from_static_str(TOPIC))
-           .await
-           .unwrap();
+   MQAdminExt::start(&mut mq_admin_ext).await?;
+   let broker_datas = MQAdminExt::examine_topic_route_info(
+       &mq_admin_ext,
+       CheetahString::from_static_str(TOPIC),
+   ).await?;
    for broker_data in broker_datas.broker_datas {
        let broker_addrs = broker_data
            .broker_addrs()
            .values()
            .cloned()
            .into_iter()
            .collect::<HashSet<CheetahString>>();
        for broker_addr in broker_addrs {
-           MQAdminExt::set_message_request_mode(
+           MQAdminExt::set_message_request_mode(
                &mq_admin_ext,
                broker_addr,
                CheetahString::from_static_str(TOPIC),
                CheetahString::from_static_str(CONSUMER_GROUP),
                MessageRequestMode::Pop,
                8,
                3_000,
            )
            .await
-           .unwrap();
+           ?;
        }
    }
    Ok(())
}

40-61: 🛠️ Refactor suggestion

Add error handling for consumer startup.

The main function's consumer startup could benefit from proper error handling.

Apply this diff to improve error handling:

#[rocketmq::main]
pub async fn main() -> Result<()> {
    //init logger
    rocketmq_common::log::init_logger();

-   switch_pop_consumer().await?;
+   if let Err(e) = switch_pop_consumer().await {
+       eprintln!("Failed to switch pop consumer: {}", e);
+       return Err(e);
+   }

    // create a producer builder with default configuration
    let builder = DefaultMQPushConsumer::builder();

    let mut consumer = builder
        .consumer_group(CONSUMER_GROUP.to_string())
        .name_server_addr(DEFAULT_NAMESRVADDR.to_string())
        // disable client side load balance, also is pop consumer
        .client_rebalance(false)
        .build();
-   consumer.subscribe(TOPIC, "*")?;
-   consumer.register_message_listener_concurrently(MyMessageListener);
-   consumer.start().await?;
+   if let Err(e) = consumer.subscribe(TOPIC, "*") {
+       eprintln!("Failed to subscribe to topic: {}", e);
+       return Err(e);
+   }
+   consumer.register_message_listener_concurrently(MyMessageListener);
+   if let Err(e) = consumer.start().await {
+       eprintln!("Failed to start consumer: {}", e);
+       return Err(e);
+   }
    let _ = wait_for_signal().await;
    Ok(())
}
🧹 Nitpick comments (1)
rocketmq-example/examples/consumer/pop_consumer.rs (1)

96-109: Add logging for message processing errors.

The message listener should log any errors that occur during message processing.

Apply this diff to improve error handling in the message listener:

impl MessageListenerConcurrently for MyMessageListener {
    fn consume_message(
        &self,
        msgs: &[&MessageExt],
        _context: &ConsumeConcurrentlyContext,
    ) -> Result<ConsumeConcurrentlyStatus> {
        for msg in msgs {
-           info!("Receive message: {:?}", msg);
+           match process_message(msg) {
+               Ok(_) => info!("Successfully processed message: {:?}", msg),
+               Err(e) => {
+                   error!("Failed to process message: {:?}, error: {}", msg, e);
+                   return Ok(ConsumeConcurrentlyStatus::ReconsumeLater);
+               }
+           }
        }
        Ok(ConsumeConcurrentlyStatus::ConsumeSuccess)
    }
}

fn process_message(msg: &MessageExt) -> Result<()> {
    info!("Processing message: {:?}", msg);
    // Add your message processing logic here
    Ok(())
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8bc3bec and ebaba4b.

📒 Files selected for processing (3)
  • rocketmq-client/src/admin/default_mq_admin_ext_impl.rs (2 hunks)
  • rocketmq-example/examples/consumer/pop_consumer.rs (1 hunks)
  • rocketmq-tools/src/admin/default_mq_admin_ext.rs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: test
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: build
  • GitHub Check: auto-approve
  • GitHub Check: build (ubuntu-latest, stable)
🔇 Additional comments (5)
rocketmq-example/examples/consumer/pop_consumer.rs (1)

65-66: LGTM! Explicit configuration of namesrv_addr.

The addition of explicit namesrv_addr configuration improves the clarity of the connection setup.

rocketmq-client/src/admin/default_mq_admin_ext_impl.rs (2)

96-115: LGTM! Constructor parameter addition improves configurability.

The addition of the admin_ext_group parameter to the constructor enhances the configurability of the DefaultMQAdminExtImpl struct.


85-93: LGTM! Struct field initialization is consistent.

The initialization of the admin_ext_group field directly from the constructor parameter maintains consistency.

rocketmq-tools/src/admin/default_mq_admin_ext.rs (2)

185-193: LGTM! Well-designed accessor methods.

The addition of inline accessor methods for client configuration follows good encapsulation practices.


62-183: LGTM! Consistent admin_ext_group initialization.

The changes ensure consistent initialization of admin_ext_group across all constructors by using a local variable.

Copy link

codecov bot commented Feb 15, 2025

Codecov Report

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

Project coverage is 28.52%. Comparing base (8bc3bec) to head (ebaba4b).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-tools/src/admin/default_mq_admin_ext.rs 0.00% 24 Missing ⚠️
...etmq-client/src/admin/default_mq_admin_ext_impl.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2555      +/-   ##
==========================================
- Coverage   28.53%   28.52%   -0.01%     
==========================================
  Files         512      512              
  Lines       74386    74405      +19     
==========================================
  Hits        21224    21224              
- Misses      53162    53181      +19     

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

Copy link
Collaborator

@rocketmq-rust-bot rocketmq-rust-bot left a comment

Choose a reason for hiding this comment

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

LGTM

@rocketmq-rust-bot rocketmq-rust-bot merged commit 38ff8ad into main Feb 15, 2025
24 of 26 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 Feb 15, 2025
@mxsm mxsm deleted the bug-2554 branch February 16, 2025 01:28
# 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 bug🐛 Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug🐛] Fix pop consumer can't start
3 participants