Skip to content

[ISSUE #1234]🐛NameServer Cannot drop a runtime in a context where blocking is not allowed#1238

Merged
rocketmq-rust-bot merged 1 commit intomainfrom
bug-1234
Nov 20, 2024
Merged

[ISSUE #1234]🐛NameServer Cannot drop a runtime in a context where blocking is not allowed#1238
rocketmq-rust-bot merged 1 commit intomainfrom
bug-1234

Conversation

@mxsm
Copy link
Copy Markdown
Owner

@mxsm mxsm commented Nov 20, 2024

Which Issue(s) This PR Fixes(Closes)

Fixes #1234

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Enhanced asynchronous capabilities of the name server for improved performance.
    • Dynamic connection timeout management for better client-server interaction.
  • Bug Fixes

    • Improved address list management to ensure accurate updates and removal of invalid entries.
  • Documentation

    • Updated method signatures for better clarity and consistency in usage.

@mxsm mxsm linked an issue Nov 20, 2024 that may be closed by this pull request
3 tasks
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 20, 2024

Walkthrough

The changes made in this pull request enhance the asynchronous functionality of the NameServerRuntime and its associated components in the rocketmq-namesrv module. The boot method now utilizes tokio::join! for concurrent execution, while the start method is wrapped in tokio::spawn for asynchronous operation. Additionally, modifications in the rocketmq-remoting module adjust connection timeout handling and the method for updating the name server address list, impacting client connection management.

Changes

File Path Change Summary
rocketmq-namesrv/src/bootstrap.rs Updated method signatures for boot, start, init_processors, and Builder methods. Enhanced boot with tokio::join! and start with tokio::spawn.
rocketmq-remoting/src/clients/rocketmq_default_impl.rs Adjusted start method to use dynamic sleep duration based on connect_timeout_millis. Modified update_name_server_address_list to extend the existing address list instead of cloning.

Assessment against linked issues

Objective Addressed Explanation
Ensure NameServerRuntime can drop in non-blocking contexts (1234)

Possibly related PRs

Suggested labels

approved, auto merge, AI review first

Suggested reviewers

  • TeslaRustor
  • SpaceXCN

Poem

In the land of code where rabbits play,
Asynchronous dreams hop through the day.
With tokio we leap, no time to waste,
NameServer's magic, a swift, joyful haste!
Address lists grow, connections align,
In the world of RocketMQ, all works fine! 🐇✨


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 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
Copy Markdown
Collaborator

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

@rocketmq-rust-bot rocketmq-rust-bot added AI review first Ai review pr first ready to review waiting-review waiting review this PR labels Nov 20, 2024
@codecov
Copy link
Copy Markdown

codecov bot commented Nov 20, 2024

Codecov Report

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

Project coverage is 18.02%. Comparing base (47e37c5) to head (bed93ae).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-namesrv/src/bootstrap.rs 0.00% 17 Missing ⚠️
...etmq-remoting/src/clients/rocketmq_default_impl.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1238      +/-   ##
==========================================
- Coverage   18.03%   18.02%   -0.01%     
==========================================
  Files         428      428              
  Lines       53549    53563      +14     
==========================================
  Hits         9655     9655              
- Misses      43894    43908      +14     

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


🚨 Try these New Features:

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

🧹 Outside diff range and nitpick comments (2)
rocketmq-namesrv/src/bootstrap.rs (1)

63-67: Remove commented code.

The old select! implementation is commented out and should be removed as it's no longer needed.

-        /*select! {
-            _ = self.name_server_runtime.start() =>{
-
-            }
-        }*/
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 63-63: rocketmq-namesrv/src/bootstrap.rs#L63
Added line #L63 was not covered by tests

rocketmq-remoting/src/clients/rocketmq_default_impl.rs (1)

Line range hint 1-999: Review architectural impact on runtime dropping bug

While the changes improve the client implementation, they don't fully address the core issue from PR #1234 regarding NameServer runtime dropping in non-blocking contexts. The current implementation still has potential blocking operations in the name server scanning loop.

Consider:

  1. Making the name server scanning truly non-blocking by using async channels for updates
  2. Implementing proper shutdown handling to ensure clean runtime dropping
  3. Adding metrics and logging for better observability of the name server connection state

Would you like me to propose a more comprehensive architectural solution?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 243-243: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L243
Added line #L243 was not covered by tests


[warning] 247-247: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L247
Added line #L247 was not covered by tests

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 47e37c5 and bed93ae.

📒 Files selected for processing (2)
  • rocketmq-namesrv/src/bootstrap.rs (3 hunks)
  • rocketmq-remoting/src/clients/rocketmq_default_impl.rs (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
rocketmq-namesrv/src/bootstrap.rs

[warning] 63-63: rocketmq-namesrv/src/bootstrap.rs#L63
Added line #L63 was not covered by tests


[warning] 67-68: rocketmq-namesrv/src/bootstrap.rs#L67-L68
Added lines #L67 - L68 were not covered by tests


[warning] 78-91: rocketmq-namesrv/src/bootstrap.rs#L78-L91
Added lines #L78 - L91 were not covered by tests

rocketmq-remoting/src/clients/rocketmq_default_impl.rs

[warning] 243-243: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L243
Added line #L243 was not covered by tests


[warning] 247-247: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L247
Added line #L247 was not covered by tests


[warning] 295-295: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L295
Added line #L295 was not covered by tests

🔇 Additional comments (2)
rocketmq-namesrv/src/bootstrap.rs (1)

Line range hint 63-91: Verify concurrent execution and shutdown behavior.

The changes correctly address the blocking issue by introducing proper async patterns. However, we should verify the complete lifecycle:

  1. Server startup doesn't block
  2. Graceful shutdown works when signal is received
  3. Resources are properly cleaned up

Let's verify the shutdown behavior:

✅ Verification successful

Based on the extensive search results, I can now provide a final assessment of the shutdown behavior in the codebase.

Proper shutdown handling is implemented with graceful cleanup

The codebase has comprehensive shutdown handling:

  1. The NameServerRuntime implements Drop trait with proper cleanup
  2. The server uses tokio's graceful shutdown pattern with:
    • tokio::join! for concurrent execution
    • Signal handling via wait_for_signal()
    • Proper resource cleanup through Drop implementations

The key components work together:

  • Shutdown struct manages shutdown state and notifications
  • Broadcast channels coordinate shutdown across components
  • Resources are properly dropped via Drop trait implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper resource cleanup in shutdown paths

# Look for Drop trait implementations
rg -A 5 "impl Drop"

# Look for shutdown/cleanup related functions
rg -A 5 "shutdown|cleanup|drop"

# Check for potential resource leaks (holding strong references)
ast-grep --pattern 'Arc::new($expr)'

Length of output: 164164

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 78-91: rocketmq-namesrv/src/bootstrap.rs#L78-L91
Added lines #L78 - L91 were not covered by tests

rocketmq-remoting/src/clients/rocketmq_default_impl.rs (1)

293-295: ⚠️ Potential issue

Fix address list management and implement shuffling

There are several issues in the name server address list update logic:

  1. The commented-out shuffling code should be implemented for proper load balancing
  2. Using extend instead of replacing the list could lead to duplicates and memory growth

Apply this fix:

- /* let mut rng = thread_rng();
- addrs.shuffle(&mut rng);*/
- self.namesrv_addr_list.mut_from_ref().extend(addrs.clone());
+ let mut rng = rand::thread_rng();
+ let mut shuffled_addrs = addrs.clone();
+ shuffled_addrs.shuffle(&mut rng);
+ self.namesrv_addr_list.mut_from_ref().clear();
+ self.namesrv_addr_list.mut_from_ref().extend(shuffled_addrs);

Let's verify the impact of these changes:

Would you like me to help create unit tests to verify this functionality?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 295-295: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L295
Added line #L295 was not covered by tests

Comment on lines +63 to 69
/*select! {
_ = self.name_server_runtime.start() =>{

}
}
}*/
tokio::join!(self.name_server_runtime.start(), wait_for_signal());
}
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 issue

Add test coverage for the boot method.

The boot method contains critical changes to fix the blocking issue, but lacks test coverage. Please add tests to verify:

  1. Concurrent execution of server start and signal handling
  2. Proper shutdown when signal is received

Would you like me to help create a test suite for this functionality?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 63-63: rocketmq-namesrv/src/bootstrap.rs#L63
Added line #L63 was not covered by tests


[warning] 67-68: rocketmq-namesrv/src/bootstrap.rs#L67-L68
Added lines #L67 - L68 were not covered by tests

Comment on lines +78 to +91
tokio::spawn(async move {
server.run(request_processor).await;
});
let namesrv = CheetahString::from_string(format!(
"{}:{}",
NetworkUtil::get_local_address().unwrap(),
self.server_config.listen_port
));
let weak_arc_mut = ArcMut::downgrade(&self.remoting_client);
self.remoting_client
.update_name_server_address_list(vec![namesrv])
.await;
self.remoting_client.start(weak_arc_mut).await;
info!("Rocketmq NameServer(Rust) started");
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 issue

Add test coverage for the start method.

The start method contains critical async functionality but lacks test coverage. Please add tests to verify:

  1. Proper server initialization and startup
  2. Correct address list update
  3. Remoting client initialization with weak reference

Would you like me to help create integration tests for this functionality?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 78-91: rocketmq-namesrv/src/bootstrap.rs#L78-L91
Added lines #L78 - L91 were not covered by tests

Comment on lines +81 to +85
let namesrv = CheetahString::from_string(format!(
"{}:{}",
NetworkUtil::get_local_address().unwrap(),
self.server_config.listen_port
));
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 issue

Improve error handling for local address resolution.

The unwrap() call on NetworkUtil::get_local_address() could panic if local address resolution fails. Consider proper error handling:

-            NetworkUtil::get_local_address().unwrap(),
+            NetworkUtil::get_local_address().map_err(|e| {
+                tracing::error!("Failed to get local address: {}", e);
+                e
+            })?,

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

Comment on lines +243 to +247
let connect_timeout_millis = self.tokio_client_config.connect_timeout_millis as u64;
self.client_runtime.get_handle().spawn(async move {
loop {
time::sleep(Duration::from_millis(1)).await;
client.scan_available_name_srv().await;
time::sleep(Duration::from_millis(connect_timeout_millis)).await;
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 suggestion

Consider separating scan interval from connection timeout

The sleep duration between name server scans is currently using the connection timeout value. While this is better than the previous 1ms interval, these are conceptually different configurations that should be separated.

Consider:

  1. Adding a separate configuration for scan interval
  2. Adding a cancellation mechanism for clean shutdown
 async fn start(&self, this: WeakArcMut<Self>) {
     if let Some(client) = this.upgrade() {
-        let connect_timeout_millis = self.tokio_client_config.connect_timeout_millis as u64;
+        let scan_interval_millis = self.tokio_client_config.name_srv_scan_interval_millis as u64;
+        let (tx, mut rx) = tokio::sync::oneshot::channel();
+        self.shutdown_tx.replace(tx);
         self.client_runtime.get_handle().spawn(async move {
             loop {
                 client.scan_available_name_srv().await;
-                time::sleep(Duration::from_millis(connect_timeout_millis)).await;
+                tokio::select! {
+                    _ = time::sleep(Duration::from_millis(scan_interval_millis)) => {},
+                    _ = &mut rx => break,
+                }
             }
         });
     }
 }

Additionally, the static analysis indicates these changes lack test coverage. Would you like me to help create unit tests for this functionality?

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

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 243-243: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L243
Added line #L243 was not covered by tests


[warning] 247-247: rocketmq-remoting/src/clients/rocketmq_default_impl.rs#L247
Added line #L247 was not covered by tests

@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved auto merge and removed ready to review waiting-review waiting review this PR labels Nov 20, 2024
@rocketmq-rust-bot rocketmq-rust-bot merged commit 3998417 into main Nov 20, 2024
@mxsm mxsm deleted the bug-1234 branch November 21, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug🐛] NameServer Cannot drop a runtime in a context where blocking is not allowed

3 participants