Skip to content

[ISSUE #3461]🚀Refactor shutdown methods to be asynchronous for improved performance and responsiveness✨ #3462

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
Jun 14, 2025

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Jun 14, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3461

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • Refactor
    • Improved the shutdown process for transactional message services to use asynchronous operations, ensuring proper completion of shutdown tasks.
    • Updated related components to support asynchronous shutdown, enhancing reliability during service termination.

@Copilot Copilot AI review requested due to automatic review settings June 14, 2025 15:30
Copy link
Contributor

coderabbitai bot commented Jun 14, 2025

Walkthrough

The changes refactor the shutdown methods for transactional message services in the RocketMQ broker to be asynchronous. Method signatures and implementations are updated to support async/await, ensuring that shutdown operations for transactional components are properly awaited and executed asynchronously.

Changes

File(s) Change Summary
rocketmq-broker/src/broker_runtime.rs Refactored shutdown logic to await the async shutdown of transactional_message_service.
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs Made shutdown and close methods async; now properly awaits batch service shutdown if present.
rocketmq-broker/src/transaction/queue/transactional_op_batch_service.rs Added new async shutdown method to TransactionalOpBatchService.
rocketmq-broker/src/transaction/transactional_message_service.rs Changed close method in trait to async.

Sequence Diagram(s)

sequenceDiagram
    participant BrokerRuntime
    participant TransactionalMessageService
    participant TransactionalOpBatchService

    BrokerRuntime->>TransactionalMessageService: shutdown().await
    TransactionalMessageService->>TransactionalMessageService: close().await
    alt If batch service present
        TransactionalMessageService->>TransactionalOpBatchService: shutdown().await
        TransactionalOpBatchService->>TransactionalOpBatchService: service_manager.shutdown().await
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Refactor shutdown methods to be asynchronous for improved performance and responsiveness (#3461)
Ensure the refactor does not introduce new bugs, update unit tests if applicable, ensure no negative performance impact, document new patterns, test in different environments (#3461) Only code changes for async refactor are present; no evidence of updated tests, documentation, or environment testing.

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

A shutdown once so quick and plain,
Now awaits, async, in the rain.
Each service bows and says goodbye,
Awaiting friends before they fly.
The broker smiles, its job well done—
Responsiveness for everyone!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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
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

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Refactor shutdown methods to be asynchronous in broker services for improved performance and responsiveness.

  • Change close() in TransactionalMessageServiceLocal to an async method.
  • Add shutdown() as an async method in TransactionalOpBatchService and implement it in DefaultTransactionalMessageService.
  • Update broker startup/shutdown logic in BrokerRuntime to await the new async shutdown methods.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
rocketmq-broker/src/transaction/transactional_message_service.rs Converted close() to async fn close() in the service trait
rocketmq-broker/src/transaction/queue/transactional_op_batch_service.rs Added pub async fn shutdown() calling service_manager.shutdown()
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs Implemented async shutdown() and async fn close() to await batch service shutdown
rocketmq-broker/src/broker_runtime.rs Updated broker shutdown to await transactional_message_service.shutdown()
Comments suppressed due to low confidence (2)

rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs:226

  • The trait defines an async close() method but the implementation exposes shutdown(); consider unifying method names (either rename close to shutdown in the trait or vice versa) for a consistent API.
    pub async fn shutdown(&mut self) {

rocketmq-broker/src/transaction/transactional_message_service.rs:111

  • Rust traits do not support async functions directly; you should annotate this trait with #[async_trait] or change close to return a boxed Future to ensure compatibility.
    async fn close(&self);

@@ -59,6 +59,10 @@ where
self.service_manager.start().await.unwrap();
}

pub async fn shutdown(&self) {
self.service_manager.shutdown().await.unwrap();
Copy link
Preview

Copilot AI Jun 14, 2025

Choose a reason for hiding this comment

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

[nitpick] Using unwrap() on a shutdown result can cause a panic; consider handling errors gracefully or logging failures instead of unwrapping.

Suggested change
self.service_manager.shutdown().await.unwrap();
if let Err(e) = self.service_manager.shutdown().await {
warn!("Failed to shut down service manager: {:?}", e);
}

Copilot uses AI. Check for mistakes.

@@ -317,7 +317,7 @@ impl BrokerRuntime {
if let Some(transactional_message_service) =
self.inner.transactional_message_service.as_mut()
{
transactional_message_service.shutdown();
transactional_message_service.shutdown().await;
Copy link
Preview

Copilot AI Jun 14, 2025

Choose a reason for hiding this comment

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

[nitpick] Ignoring potential errors from shutdown() might mask failures; consider handling or logging errors returned by shutdown() instead of silently awaiting.

Copilot uses AI. Check for mistakes.

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

🧹 Nitpick comments (1)
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs (1)

226-228: Redundant public shutdown wrapper—consider consolidating with trait‐level close()

shutdown() is only delegating to self.close().await, so the repo now exposes two names for the same concern (close and shutdown). This increases the cognitive load for callers and makes the public surface inconsistent with the TransactionalMessageService trait, which already defines close().

If an explicit mutable‐borrow variant is needed (e.g. to take() the option – see next comment), consider:

  1. Moving the resource‐cleanup logic into shutdown(&mut self) and dropping close() from the trait, or
  2. Keeping only close() and having external code call it directly.

Either way keeps a single authoritative shutdown entry-point.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c6f28a and 7552d63.

📒 Files selected for processing (4)
  • rocketmq-broker/src/broker_runtime.rs (1 hunks)
  • rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs (2 hunks)
  • rocketmq-broker/src/transaction/queue/transactional_op_batch_service.rs (1 hunks)
  • rocketmq-broker/src/transaction/transactional_message_service.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
rocketmq-broker/src/transaction/transactional_message_service.rs (1)
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs (1)
  • close (1128-1132)
rocketmq-broker/src/transaction/queue/transactional_op_batch_service.rs (2)
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs (1)
  • shutdown (226-228)
rocketmq-broker/src/broker_runtime.rs (1)
  • shutdown (251-278)
⏰ 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, stable)
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: auto-approve
  • GitHub Check: test
  • GitHub Check: build
🔇 Additional comments (1)
rocketmq-broker/src/transaction/transactional_message_service.rs (1)

110-112: Trait change is breaking – ensure all implementors are updated & re-exported

close is now async, which alters the autogenerated trait_variant surface.
Double-check that every downstream implementation has the new signature and that
public re-exports (pub use …) are updated to avoid semver regressions.

Comment on lines +62 to +64
pub async fn shutdown(&self) {
self.service_manager.shutdown().await.unwrap();
}
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

Avoid panicking during shutdown – handle the Result instead of unwrapping

A failure during shutdown should not bring the whole broker down.
Replacing unwrap() with graceful error handling (log & return) will keep the node responsive even if the inner service fails.

-    pub async fn shutdown(&self) {
-        self.service_manager.shutdown().await.unwrap();
+    pub async fn shutdown(&self) {
+        if let Err(e) = self.service_manager.shutdown().await {
+            tracing::error!("TransactionalOpBatchService shutdown failed: {e:?}");
+        }
     }
📝 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
pub async fn shutdown(&self) {
self.service_manager.shutdown().await.unwrap();
}
pub async fn shutdown(&self) {
if let Err(e) = self.service_manager.shutdown().await {
tracing::error!("TransactionalOpBatchService shutdown failed: {e:?}");
}
}
🤖 Prompt for AI Agents
In rocketmq-broker/src/transaction/queue/transactional_op_batch_service.rs at
lines 62 to 64, the shutdown method currently uses unwrap() on the result of
service_manager.shutdown(), which can cause a panic if shutdown fails. Replace
unwrap() with proper error handling by matching on the Result, logging any error
encountered, and returning gracefully without panicking to ensure the broker
remains responsive even if shutdown encounters issues.

Comment on lines 317 to 321
if let Some(transactional_message_service) =
self.inner.transactional_message_service.as_mut()
{
transactional_message_service.shutdown();
transactional_message_service.shutdown().await;
}
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

Hold-and-await on a &mut borrow risks future borrow-checker pain

self.inner.transactional_message_service.as_mut() yields a mutable borrow that is
held across the .await.
While this compiles today, it prevents any code inside shutdown() from
re-borrowing self.inner (directly or indirectly) and makes subsequent
refactors harder.

Consider taking ownership (or a clone) first and releasing the borrow before
awaiting:

if let Some(service) = self.inner.transactional_message_service.take() {
    service.shutdown().await;
}

This pattern also guarantees the field is None afterwards, so shutdown is
performed exactly once.

🤖 Prompt for AI Agents
In rocketmq-broker/src/broker_runtime.rs around lines 317 to 321, the code holds
a mutable borrow of self.inner.transactional_message_service across an await,
which can cause borrow-checker issues. To fix this, take ownership of the
transactional_message_service by using .take() to replace the Option with None
before awaiting shutdown, ensuring the mutable borrow is released before the
await and that shutdown is called exactly once.

Comment on lines +1128 to 1132
async fn close(&self) {
if let Some(batch_service) = &self.transactional_op_batch_service {
batch_service.shutdown().await
}
}
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

transactional_op_batch_service is never dropped – potential resource leak

close(&self) calls batch_service.shutdown().await but retains the Some(...) value inside the Option, keeping any internal state and allocations alive for the remainder of the broker’s lifetime.
Because close only borrows &self, it cannot take() the value.

A minimal, non-breaking refactor is to move the ownership-dropping logic into the shutdown(&mut self) wrapper where a mutable borrow already exists:

-pub async fn shutdown(&mut self) {
-    self.close().await
+pub async fn shutdown(&mut self) {
+    if let Some(batch_service) = self.transactional_op_batch_service.take() {
+        batch_service.shutdown().await;
+    }
 }

This:

• Ensures the service is dropped after its async shutdown completes.
• Prevents accidental double-shutdowns.
• Frees memory and wakes any Weak references earlier.

If you keep both entry-points, make close() simply call the new shutdown(&mut self) via async { … } to centralise the logic.

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

🤖 Prompt for AI Agents
In
rocketmq-broker/src/transaction/queue/default_transactional_message_service.rs
around lines 1128 to 1132, the close(&self) method calls shutdown on
transactional_op_batch_service but does not drop it, causing a potential
resource leak. Refactor by moving the shutdown and dropping logic into a new
shutdown(&mut self) method where you have mutable access, allowing you to take()
the Option and drop it after awaiting shutdown. Then, have close() call this
shutdown(&mut self) asynchronously to centralize the shutdown and dropping
logic, ensuring the service is properly dropped and resources freed.

Copy link

codecov bot commented Jun 14, 2025

Codecov Report

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

Project coverage is 26.47%. Comparing base (3c6f28a) to head (7552d63).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ion/queue/default_transactional_message_service.rs 0.00% 6 Missing ⚠️
...ransaction/queue/transactional_op_batch_service.rs 0.00% 3 Missing ⚠️
rocketmq-broker/src/broker_runtime.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3462      +/-   ##
==========================================
- Coverage   26.47%   26.47%   -0.01%     
==========================================
  Files         545      545              
  Lines       77749    77754       +5     
==========================================
  Hits        20583    20583              
- Misses      57166    57171       +5     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 136fe59 into main Jun 14, 2025
23 of 24 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 Jun 14, 2025
@mxsm mxsm deleted the refactor-3461 branch June 14, 2025 15:42
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 refactor♻️ refactor code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Refactor♻️]Refactor shutdown methods to be asynchronous for improved performance and responsiveness
3 participants