Skip to content

[ISSUE #3503]🚀Implement General HA components and complete AutoSwitch HA implementation✨#3504

Merged
rocketmq-rust-bot merged 1 commit intomainfrom
feature-3503
Jun 22, 2025
Merged

[ISSUE #3503]🚀Implement General HA components and complete AutoSwitch HA implementation✨#3504
rocketmq-rust-bot merged 1 commit intomainfrom
feature-3503

Conversation

@mxsm
Copy link
Owner

@mxsm mxsm commented Jun 22, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3503

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Introduced new high-availability (HA) client and connection types, including general and auto-switch variants, to enhance HA capabilities.
    • Added new initialization logic for HA services, allowing for explicit setup of underlying components.
  • Refactor

    • Updated internal structure to support modular HA client and connection management, improving flexibility for future enhancements.
  • Chores

    • Included placeholder implementations for new HA client methods, laying groundwork for future functionality.

Copilot AI review requested due to automatic review settings June 22, 2025 07:43
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 22, 2025

Walkthrough

This change introduces new general and AutoSwitch High Availability (HA) components, including unified client and connection managers, and expands module declarations for better organization. It adds struct definitions and trait stubs for AutoSwitch HA, updates initialization logic for DefaultHAService, and ensures proper service integration and modular separation for HA strategies.

Changes

Files / Modules Change Summary
rocketmq-store/src/ha.rs, rocketmq-store/src/ha/auto_switch.rs Added module declarations for general_ha_client, general_ha_connection, auto_switch_ha_client, and auto_switch_ha_connection.
rocketmq-store/src/ha/general_ha_client.rs, rocketmq-store/src/ha/general_ha_connection.rs Added new public structs: GeneralHAClient and GeneralHAConnection, each managing Default and AutoSwitch variants.
rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs Added AutoSwitchHAClient struct and HAClient trait implementation with method stubs (all todo!).
rocketmq-store/src/ha/auto_switch/auto_switch_ha_connection.rs Added AutoSwitchHAConnection struct (no methods or fields yet).
rocketmq-store/src/ha/default_ha_service.rs Added init method to DefaultHAService for message store integration.
rocketmq-store/src/ha/general_ha_service.rs Updated init logic to initialize DefaultHAService using its new init method and propagate errors.

Sequence Diagram(s)

sequenceDiagram
    participant Config
    participant GeneralHAService
    participant DefaultHAService
    participant AutoSwitchHAClient
    participant GeneralHAClient

    Config->>GeneralHAService: Provide configuration
    GeneralHAService->>DefaultHAService: init(message_store)
    DefaultHAService-->>GeneralHAService: Result (HAResult<()>)
    GeneralHAService-->>Config: Service ready

    Note over GeneralHAClient,AutoSwitchHAClient: GeneralHAClient manages DefaultHAClient and AutoSwitchHAClient based on mode
Loading

Assessment against linked issues

Objective Addressed Explanation
General HA Components: Unified HA client and connection managers (GeneralHAClient, GeneralHAConnection) (#3503)
AutoSwitch HA Implementation: AutoSwitchHAClient, AutoSwitchHAConnection, trait implementation, module organization (#3503)
Enhanced Service Integration: DefaultHAService init, GeneralHAService initialization, module declarations (#3503)
Architecture Improvements: Layered architecture, modular design, visibility controls (#3503)

Poem

In burrows deep, new modules grow,
With clients and connections all in a row.
AutoSwitch and General, both take their place,
Unified HA, a hoppity race!
Services now start with a cheer,
The code is clean—let’s leap into a new HA frontier!
🐇✨

✨ 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-robot rocketmq-rust-robot added the feature🚀 Suggest an idea for this project. label Jun 22, 2025
@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 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

This PR implements general HA components and completes the AutoSwitch HA implementation to address issue #3503. Key changes include initializing DefaultHAService with an init method, introducing GeneralHAConnection and GeneralHAClient modules, and integrating new auto switch modules into the HA namespace.

  • Introduces initialization for DefaultHAService by calling init with a message store.
  • Adds new modules for general HA connection and client functionalities.
  • Integrates auto switch HA components into the overall HA module.

Reviewed Changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
rocketmq-store/src/ha/general_ha_service.rs Updates DefaultHAService initialization with an init call.
rocketmq-store/src/ha/general_ha_connection.rs Adds a new structure for general HA connection handling.
rocketmq-store/src/ha/general_ha_client.rs Introduces a new structure for general HA client handling.
rocketmq-store/src/ha/default_ha_service.rs Adds an empty init method to DefaultHAService for future details.
rocketmq-store/src/ha/auto_switch/auto_switch_ha_connection.rs Introduces the AutoSwitchHAConnection struct.
rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs Implements an AutoSwitchHAClient with todo!() placeholders.
rocketmq-store/src/ha/auto_switch.rs Adds module declarations for auto switch HA features.
rocketmq-store/src/ha.rs Integrates the new general HA modules into the HA namespace.
Comments suppressed due to low confidence (1)

rocketmq-store/src/ha/default_ha_service.rs:66

  • Consider adding a comment to clarify that the init function is a stub and highlight the intended initialization steps for DefaultHAService to improve maintainability.
    pub(crate) fn init(&mut self, message_store: ArcMut<LocalFileMessageStore>) -> HAResult<()> {

Comment on lines +25 to +29
todo!()
}

async fn shutdown(&self) {
todo!()
Copy link

Copilot AI Jun 22, 2025

Choose a reason for hiding this comment

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

Multiple functions currently use todo!(); please ensure that these stubs are properly implemented before production deployment to avoid runtime panics.

Suggested change
todo!()
}
async fn shutdown(&self) {
todo!()
// Initialize the client, e.g., set up connections or resources.
println!("AutoSwitchHAClient started.");
}
async fn shutdown(&self) {
// Release resources and close connections.
println!("AutoSwitchHAClient shut down.");

Copilot uses AI. Check for mistakes.
@codecov
Copy link

codecov bot commented Jun 22, 2025

Codecov Report

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

Project coverage is 26.27%. Comparing base (b48f78b) to head (20ee624).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...-store/src/ha/auto_switch/auto_switch_ha_client.rs 0.00% 26 Missing ⚠️
rocketmq-store/src/ha/default_ha_service.rs 0.00% 3 Missing ⚠️
rocketmq-store/src/ha/general_ha_service.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3504      +/-   ##
==========================================
- Coverage   26.28%   26.27%   -0.02%     
==========================================
  Files         550      551       +1     
  Lines       78341    78372      +31     
==========================================
  Hits        20593    20593              
- Misses      57748    57779      +31     

☔ 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
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: 6

🧹 Nitpick comments (4)
rocketmq-store/src/ha/auto_switch/auto_switch_ha_connection.rs (1)

17-17: Complete the AutoSwitchHAConnection implementation.

This appears to be a stub implementation. The struct lacks fields, methods, and trait implementations needed for HA connection functionality.

Would you like me to help design the structure based on existing HA connection patterns in the codebase, or should this be tracked as a TODO for future implementation?

rocketmq-store/src/ha/default_ha_service.rs (2)

17-32: Remove duplicate license header.

There are duplicate Apache License headers in this file (lines 1-16 and 17-32). Please remove the duplicate.

-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */

66-69: Implement the init method functionality.

The init method is currently a placeholder. Consider implementing the actual initialization logic or documenting the expected behavior.

Would you like me to help design the initialization logic based on the message store parameter and HA service requirements?

rocketmq-store/src/ha/general_ha_connection.rs (1)

21-24: Consider adding documentation and common trait implementations.

The struct lacks documentation explaining its purpose and when to use each connection type. Also consider implementing common traits for better usability.

+/// General HA connection that can hold either a default or auto-switch HA connection.
+/// This allows for flexible HA strategies within the RocketMQ store.
+#[derive(Debug, Clone)]
 pub struct GeneralHAConnection {
     default_ha_connection: Option<DefaultHAConnection>,
     auto_switch_ha_connection: Option<AutoSwitchHAConnection>,
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b48f78b and 20ee624.

📒 Files selected for processing (8)
  • rocketmq-store/src/ha.rs (1 hunks)
  • rocketmq-store/src/ha/auto_switch.rs (1 hunks)
  • rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs (1 hunks)
  • rocketmq-store/src/ha/auto_switch/auto_switch_ha_connection.rs (1 hunks)
  • rocketmq-store/src/ha/default_ha_service.rs (2 hunks)
  • rocketmq-store/src/ha/general_ha_client.rs (1 hunks)
  • rocketmq-store/src/ha/general_ha_connection.rs (1 hunks)
  • rocketmq-store/src/ha/general_ha_service.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build
  • GitHub Check: auto-approve
  • GitHub Check: build (ubuntu-latest, stable)
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: test
🔇 Additional comments (3)
rocketmq-store/src/ha.rs (1)

23-24: LGTM! Clean module organization.

The new module declarations follow the existing pattern and use appropriate visibility for internal crate access.

rocketmq-store/src/ha/auto_switch.rs (1)

17-18: Good architectural organization.

The new module declarations complete the auto-switch HA component trio (service, client, connection) and follow consistent naming conventions.

rocketmq-store/src/ha/general_ha_service.rs (1)

52-54: Excellent initialization pattern.

The updated initialization logic properly creates a mutable instance, initializes it with error handling, and only assigns after successful initialization. This follows good initialization practices.

Comment on lines +21 to +24
pub struct GeneralHAConnection {
default_ha_connection: Option<DefaultHAConnection>,
auto_switch_ha_connection: Option<AutoSwitchHAConnection>,
}
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

Add constructor methods and accessor functions for the struct.

The GeneralHAConnection struct currently has private fields with no way to construct or access them. Consider adding constructor methods and accessors to make the struct usable.

 pub struct GeneralHAConnection {
     default_ha_connection: Option<DefaultHAConnection>,
     auto_switch_ha_connection: Option<AutoSwitchHAConnection>,
 }
+
+impl GeneralHAConnection {
+    pub fn new() -> Self {
+        Self {
+            default_ha_connection: None,
+            auto_switch_ha_connection: None,
+        }
+    }
+
+    pub fn with_default(connection: DefaultHAConnection) -> Self {
+        Self {
+            default_ha_connection: Some(connection),
+            auto_switch_ha_connection: None,
+        }
+    }
+
+    pub fn with_auto_switch(connection: AutoSwitchHAConnection) -> Self {
+        Self {
+            default_ha_connection: None,
+            auto_switch_ha_connection: Some(connection),
+        }
+    }
+
+    pub fn get_default_connection(&self) -> Option<&DefaultHAConnection> {
+        self.default_ha_connection.as_ref()
+    }
+
+    pub fn get_auto_switch_connection(&self) -> Option<&AutoSwitchHAConnection> {
+        self.auto_switch_ha_connection.as_ref()
+    }
+}
📝 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 struct GeneralHAConnection {
default_ha_connection: Option<DefaultHAConnection>,
auto_switch_ha_connection: Option<AutoSwitchHAConnection>,
}
pub struct GeneralHAConnection {
default_ha_connection: Option<DefaultHAConnection>,
auto_switch_ha_connection: Option<AutoSwitchHAConnection>,
}
impl GeneralHAConnection {
pub fn new() -> Self {
Self {
default_ha_connection: None,
auto_switch_ha_connection: None,
}
}
pub fn with_default(connection: DefaultHAConnection) -> Self {
Self {
default_ha_connection: Some(connection),
auto_switch_ha_connection: None,
}
}
pub fn with_auto_switch(connection: AutoSwitchHAConnection) -> Self {
Self {
default_ha_connection: None,
auto_switch_ha_connection: Some(connection),
}
}
pub fn get_default_connection(&self) -> Option<&DefaultHAConnection> {
self.default_ha_connection.as_ref()
}
pub fn get_auto_switch_connection(&self) -> Option<&AutoSwitchHAConnection> {
self.auto_switch_ha_connection.as_ref()
}
}
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/general_ha_connection.rs around lines 21 to 24, the
GeneralHAConnection struct has private fields without any constructor or
accessor methods. Add a constructor method (e.g., new) to initialize the struct
with given DefaultHAConnection and AutoSwitchHAConnection options, and implement
getter methods to access these private fields safely from outside the struct.

Comment on lines +22 to +23
default_ha_service: Option<DefaultHAClient>,
auto_switch_ha_service: Option<AutoSwitchHAClient>,
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

Fix naming inconsistency between field names and types.

The field names use "service" suffix but the types are "Client" types. This creates confusion and should be corrected for consistency.

 pub struct GeneralHAClient {
-    default_ha_service: Option<DefaultHAClient>,
-    auto_switch_ha_service: Option<AutoSwitchHAClient>,
+    default_ha_client: Option<DefaultHAClient>,
+    auto_switch_ha_client: Option<AutoSwitchHAClient>,
 }
📝 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
default_ha_service: Option<DefaultHAClient>,
auto_switch_ha_service: Option<AutoSwitchHAClient>,
pub struct GeneralHAClient {
default_ha_client: Option<DefaultHAClient>,
auto_switch_ha_client: Option<AutoSwitchHAClient>,
}
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/general_ha_client.rs around lines 22 to 23, the field
names use the suffix "service" while their types use "Client," causing
inconsistency. Rename the fields from default_ha_service and
auto_switch_ha_service to default_ha_client and auto_switch_ha_client
respectively to match the type names and maintain clear, consistent naming.

Comment on lines +21 to +24
pub struct GeneralHAClient {
default_ha_service: Option<DefaultHAClient>,
auto_switch_ha_service: Option<AutoSwitchHAClient>,
}
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

Add constructor methods and accessor functions for the struct.

Similar to GeneralHAConnection, this struct needs constructor methods and accessors to be usable. The implementation pattern should be consistent across both general HA structs.

 pub struct GeneralHAClient {
-    default_ha_service: Option<DefaultHAClient>,
-    auto_switch_ha_service: Option<AutoSwitchHAClient>,
+    default_ha_client: Option<DefaultHAClient>,
+    auto_switch_ha_client: Option<AutoSwitchHAClient>,
 }
+
+impl GeneralHAClient {
+    pub fn new() -> Self {
+        Self {
+            default_ha_client: None,
+            auto_switch_ha_client: None,
+        }
+    }
+
+    pub fn with_default(client: DefaultHAClient) -> Self {
+        Self {
+            default_ha_client: Some(client),
+            auto_switch_ha_client: None,
+        }
+    }
+
+    pub fn with_auto_switch(client: AutoSwitchHAClient) -> Self {
+        Self {
+            default_ha_client: None,
+            auto_switch_ha_client: Some(client),
+        }
+    }
+
+    pub fn get_default_client(&self) -> Option<&DefaultHAClient> {
+        self.default_ha_client.as_ref()
+    }
+
+    pub fn get_auto_switch_client(&self) -> Option<&AutoSwitchHAClient> {
+        self.auto_switch_ha_client.as_ref()
+    }
+}
📝 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 struct GeneralHAClient {
default_ha_service: Option<DefaultHAClient>,
auto_switch_ha_service: Option<AutoSwitchHAClient>,
}
pub struct GeneralHAClient {
default_ha_client: Option<DefaultHAClient>,
auto_switch_ha_client: Option<AutoSwitchHAClient>,
}
impl GeneralHAClient {
/// Creates an empty client with no HA backends configured.
pub fn new() -> Self {
Self {
default_ha_client: None,
auto_switch_ha_client: None,
}
}
/// Creates a client using the given `DefaultHAClient`.
pub fn with_default(client: DefaultHAClient) -> Self {
Self {
default_ha_client: Some(client),
auto_switch_ha_client: None,
}
}
/// Creates a client using the given `AutoSwitchHAClient`.
pub fn with_auto_switch(client: AutoSwitchHAClient) -> Self {
Self {
default_ha_client: None,
auto_switch_ha_client: Some(client),
}
}
/// Returns a reference to the default HA client, if configured.
pub fn get_default_client(&self) -> Option<&DefaultHAClient> {
self.default_ha_client.as_ref()
}
/// Returns a reference to the auto‐switch HA client, if configured.
pub fn get_auto_switch_client(&self) -> Option<&AutoSwitchHAClient> {
self.auto_switch_ha_client.as_ref()
}
}
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/general_ha_client.rs around lines 21 to 24, the
GeneralHAClient struct lacks constructor methods and accessor functions, which
are necessary for consistent usage similar to GeneralHAConnection. Add a
constructor method to initialize GeneralHAClient with appropriate parameters and
implement accessor functions to retrieve references to default_ha_service and
auto_switch_ha_service fields, following the pattern used in GeneralHAConnection
for consistency.

Comment on lines +23 to +75
impl HAClient for AutoSwitchHAClient {
async fn start(&self) {
todo!()
}

async fn shutdown(&self) {
todo!()
}

async fn wakeup(&self) {
todo!()
}

async fn update_master_address(&self, new_address: &str) {
todo!()
}

async fn update_ha_master_address(&self, new_address: &str) {
todo!()
}

fn get_master_address(&self) -> String {
todo!()
}

fn get_ha_master_address(&self) -> String {
todo!()
}

fn get_last_read_timestamp(&self) -> i64 {
todo!()
}

fn get_last_write_timestamp(&self) -> i64 {
todo!()
}

fn get_current_state(&self) -> HAConnectionState {
todo!()
}

fn change_current_state(&self, ha_connection_state: HAConnectionState) {
todo!()
}

async fn close_master(&self) {
todo!()
}

fn get_transferred_byte_in_second(&self) -> i64 {
todo!()
}
}
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

Add documentation explaining the AutoSwitch HA strategy.

The implementation lacks documentation explaining how the AutoSwitch HA client differs from the default HA client and what auto-switching behavior it should provide.

+/// AutoSwitch HA Client that automatically switches between master nodes
+/// based on availability and performance metrics.
+/// 
+/// This client implements intelligent failover logic to ensure high availability
+/// of the RocketMQ broker by monitoring connection health and switching to
+/// backup masters when the primary master becomes unavailable.
 pub struct AutoSwitchHAClient {
     // ... fields
 }

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

🤖 Prompt for AI Agents
In rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs between lines 23
and 75, add documentation comments to the AutoSwitchHAClient implementation.
Explain the purpose of the AutoSwitch HA client, how it differs from the default
HA client, and describe the auto-switching behavior it provides. Place these
comments above the impl block or each method as appropriate to clarify the
design and functionality for future maintainers.

use crate::ha::ha_client::HAClient;
use crate::ha::ha_connection_state::HAConnectionState;

pub struct AutoSwitchHAClient;
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

Add internal fields to support HA client functionality.

The AutoSwitchHAClient struct is currently empty but needs internal state to manage HA operations like master addresses, connection state, timestamps, etc.

+use std::sync::{Arc, Mutex};
+
-pub struct AutoSwitchHAClient;
+pub struct AutoSwitchHAClient {
+    master_address: Arc<Mutex<String>>,
+    ha_master_address: Arc<Mutex<String>>,
+    last_read_timestamp: Arc<Mutex<i64>>,
+    last_write_timestamp: Arc<Mutex<i64>>,
+    current_state: Arc<Mutex<HAConnectionState>>,
+    transferred_bytes: Arc<Mutex<i64>>,
+}
+
+impl AutoSwitchHAClient {
+    pub fn new() -> Self {
+        Self {
+            master_address: Arc::new(Mutex::new(String::new())),
+            ha_master_address: Arc::new(Mutex::new(String::new())),
+            last_read_timestamp: Arc::new(Mutex::new(0)),
+            last_write_timestamp: Arc::new(Mutex::new(0)),
+            current_state: Arc::new(Mutex::new(HAConnectionState::default())),
+            transferred_bytes: Arc::new(Mutex::new(0)),
+        }
+    }
+}
📝 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 struct AutoSwitchHAClient;
use crate::ha_client::{HAClient, HAConnectionState};
use std::sync::{Arc, Mutex};
pub struct AutoSwitchHAClient {
master_address: Arc<Mutex<String>>,
ha_master_address: Arc<Mutex<String>>,
last_read_timestamp: Arc<Mutex<i64>>,
last_write_timestamp: Arc<Mutex<i64>>,
current_state: Arc<Mutex<HAConnectionState>>,
transferred_bytes: Arc<Mutex<i64>>,
}
impl AutoSwitchHAClient {
pub fn new() -> Self {
Self {
master_address: Arc::new(Mutex::new(String::new())),
ha_master_address: Arc::new(Mutex::new(String::new())),
last_read_timestamp: Arc::new(Mutex::new(0)),
last_write_timestamp: Arc::new(Mutex::new(0)),
current_state: Arc::new(Mutex::new(HAConnectionState::default())),
transferred_bytes: Arc::new(Mutex::new(0)),
}
}
}
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs at line 21, the
AutoSwitchHAClient struct is empty and lacks the necessary internal fields to
manage HA client functionality. Add fields such as master addresses, connection
state, and timestamps to this struct to properly support HA operations and
maintain internal state.

Comment on lines +24 to +75
async fn start(&self) {
todo!()
}

async fn shutdown(&self) {
todo!()
}

async fn wakeup(&self) {
todo!()
}

async fn update_master_address(&self, new_address: &str) {
todo!()
}

async fn update_ha_master_address(&self, new_address: &str) {
todo!()
}

fn get_master_address(&self) -> String {
todo!()
}

fn get_ha_master_address(&self) -> String {
todo!()
}

fn get_last_read_timestamp(&self) -> i64 {
todo!()
}

fn get_last_write_timestamp(&self) -> i64 {
todo!()
}

fn get_current_state(&self) -> HAConnectionState {
todo!()
}

fn change_current_state(&self, ha_connection_state: HAConnectionState) {
todo!()
}

async fn close_master(&self) {
todo!()
}

fn get_transferred_byte_in_second(&self) -> i64 {
todo!()
}
}
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

Replace todo!() stubs with basic implementations to prevent runtime panics.

All methods currently use todo!() which will panic if called. Consider implementing basic functionality or at least safe defaults to make the code usable during development.

Here's an example of implementing some basic methods:

 impl HAClient for AutoSwitchHAClient {
     async fn start(&self) {
-        todo!()
+        // TODO: Implement AutoSwitch HA client startup logic
+        println!("AutoSwitchHAClient: start() called");
     }
 
     async fn shutdown(&self) {
-        todo!()
+        // TODO: Implement AutoSwitch HA client shutdown logic
+        println!("AutoSwitchHAClient: shutdown() called");
     }
 
     fn get_master_address(&self) -> String {
-        todo!()
+        self.master_address.lock().unwrap().clone()
     }
 
     fn get_ha_master_address(&self) -> String {
-        todo!()
+        self.ha_master_address.lock().unwrap().clone()
     }
 
     fn get_last_read_timestamp(&self) -> i64 {
-        todo!()
+        *self.last_read_timestamp.lock().unwrap()
     }
 
     fn get_last_write_timestamp(&self) -> i64 {
-        todo!()
+        *self.last_write_timestamp.lock().unwrap()
     }
 
     fn get_current_state(&self) -> HAConnectionState {
-        todo!()
+        *self.current_state.lock().unwrap()
     }
🤖 Prompt for AI Agents
In rocketmq-store/src/ha/auto_switch/auto_switch_ha_client.rs between lines 24
and 75, all methods currently use todo!() which causes runtime panics if called.
Replace these todo!() stubs with basic implementations or safe default returns
to prevent panics during development. For async methods, provide minimal async
blocks that do nothing or log a placeholder; for getters, return default values
like empty strings or zero; for state-related methods, return a default
HAConnectionState or update an internal state variable accordingly. This will
make the code safe to call and easier to extend later.

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 644d4ea into main Jun 22, 2025
22 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 22, 2025
@mxsm mxsm deleted the feature-3503 branch June 26, 2025 03:34
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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature🚀] Implement General HA components and complete AutoSwitch HA implementation

4 participants