Skip to content

[ISSUE #6278]🚀Implement BrokerConsumeStats command in rocketmq-admin-core#6373

Open
WaterWhisperer wants to merge 1 commit intomxsm:mainfrom
WaterWhisperer:feat-6278
Open

[ISSUE #6278]🚀Implement BrokerConsumeStats command in rocketmq-admin-core#6373
WaterWhisperer wants to merge 1 commit intomxsm:mainfrom
WaterWhisperer:feat-6278

Conversation

@WaterWhisperer
Copy link
Contributor

@WaterWhisperer WaterWhisperer commented Feb 18, 2026

Which Issue(s) This PR Fixes(Closes)

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features

    • Added brokerConsumeStats command to the admin tool, enabling retrieval of broker consumption statistics with configurable options for broker address, timeout, and diff level filtering.
  • Chores

    • Refactored workspace dependencies and updated configuration formatting for improved maintainability.

@rocketmq-rust-bot
Copy link
Collaborator

🔊@WaterWhisperer 🚀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💥.

@rocketmq-rust-robot rocketmq-rust-robot added Difficulty level/Moderate Moderate difficult ISSUE feature🚀 Suggest an idea for this project. labels Feb 18, 2026
@codecov
Copy link

codecov bot commented Feb 18, 2026

Codecov Report

❌ Patch coverage is 0% with 78 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.40%. Comparing base (8c801c3) to head (1e5065e).

Files with missing lines Patch % Lines
...roker_commands/broker_consume_stats_sub_command.rs 0.00% 72 Missing ⚠️
...rocketmq-admin/rocketmq-admin-core/src/commands.rs 0.00% 5 Missing ⚠️
...ocketmq-admin-core/src/commands/broker_commands.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6373      +/-   ##
==========================================
- Coverage   42.42%   42.40%   -0.03%     
==========================================
  Files         922      923       +1     
  Lines      129893   129971      +78     
==========================================
+ Hits        55109    55110       +1     
- Misses      74784    74861      +77     

☔ 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
Owner

@mxsm mxsm left a comment

Choose a reason for hiding this comment

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

@WaterWhisperer Pls fix conflicts

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 18, 2026

Walkthrough

This pull request implements a new BrokerConsumeStats command for querying broker consumption statistics in the rocketmq-admin tool, alongside dependency updates and Cargo.toml formatting adjustments across the workspace.

Changes

Cohort / File(s) Summary
Cargo.toml Formatting & Alignment
Cargo.toml, rocketmq-broker/Cargo.toml, rocketmq-example/Cargo.toml
Whitespace realignment and consistent indentation across workspace members and dependencies; adds resolver = "3" to rocketmq-example; no semantic changes.
Dependency Management
rocketmq-dashboard/rocketmq-dashboard-common/Cargo.toml, rocketmq-tools/rocketmq-admin/rocketmq-admin-cli/Cargo.toml
Removes rocketmq-common, rocketmq-client-rust, rocketmq-remoting, tokio, serde_json, tracing from dashboard-common; removes rocketmq-tools and tokio from admin-cli; updates [[bin]] section with explicit path.
Dependency Additions
rocketmq-tools/rocketmq-admin/rocketmq-admin-core/Cargo.toml
Adds chrono = "0.4" dependency.
BrokerConsumeStats Command Implementation
rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands.rs, rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands.rs, rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs
Adds new BrokerConsumeStats variant to BrokerCommands enum; introduces BrokerConsumeStatsSubCommand struct implementing CommandExecute trait with logic to initialize admin client, fetch broker consume stats, format and filter results by diff level, and display tabular output with timestamp formatting.

Sequence Diagram

sequenceDiagram
    participant User as CLI User
    participant CMD as BrokerConsumeStats<br/>Command
    participant Admin as MQAdminExt
    participant Broker as Broker

    User->>CMD: Execute with broker address & options
    CMD->>Admin: Initialize DefaultMQAdminExt
    CMD->>Admin: Start admin client
    Admin->>Broker: Fetch consume statistics
    Broker-->>Admin: Return stats (topics, groups, queues, offsets)
    Admin-->>CMD: Stats data
    CMD->>CMD: Filter & format by diff_level
    CMD->>CMD: Format timestamps for display
    CMD->>User: Print table (topic, group, broker, queue, offset, diff, time)
    CMD->>Admin: Shutdown admin client
    CMD-->>User: Operation result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 A broker now speaks of consumption stats true,
With queues and offsets sorted just right for you,
We filtered and formatted with diff levels in sight,
The telemetry flows, the admin feels light! 📊✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Several formatting and dependency changes in Cargo.toml files appear unrelated to the BrokerConsumeStats implementation objective, including workspace formatting, dependency removals in rocketmq-dashboard-common, and resolver configuration additions. Remove or justify out-of-scope changes: workspace formatting in root Cargo.toml, dependency removals in rocketmq-dashboard-common, and resolver configuration in rocketmq-example. Focus PR on BrokerConsumeStats implementation only.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: implementing the BrokerConsumeStats command in rocketmq-admin-core, which matches the linked issue #6278 and the primary objective of this PR.
Linked Issues check ✅ Passed The PR implements all primary coding requirements from issue #6278: added BrokerConsumeStats command with broker querying, consumption details display, filtering by diff level, and proper module organization under broker_commands.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (3)
rocketmq-tools/rocketmq-admin/rocketmq-admin-core/Cargo.toml (1)

50-50: Add chrono to workspace dependencies for consistency.

All other crates in this workspace consume dependencies via { workspace = true }. Adding chrono = "0.4" directly here creates a version-management inconsistency.

♻️ Proposed fix

In the root Cargo.toml under [workspace.dependencies]:

+chrono = "0.4"

Then in rocketmq-admin-core/Cargo.toml:

-chrono         = "0.4"
+chrono.workspace = true
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/Cargo.toml` at line 50,
Remove the direct dependency declaration chrono = "0.4" from
rocketmq-admin-core/Cargo.toml and instead add chrono = "0.4" under the root
Cargo.toml `[workspace.dependencies]`, then update
rocketmq-admin-core/Cargo.toml to consume chrono with `{ workspace = true }`;
reference the chrono package name and the workspace.dependencies section to
locate where to move the version declaration and the
rocketmq-admin-core/Cargo.toml to change the local dependency entry.
rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs (2)

51-58: is_order should be typed as bool, not String.

Declaring is_order: String and parsing it manually with unwrap_or(false) means any invalid input (e.g., "yes", "1") silently falls back to false with no user-visible error. Clap handles bool natively with default_value_t.

♻️ Proposed fix
-    #[arg(
-        short = 'o',
-        long = "order",
-        required = false,
-        default_value = "false",
-        help = "order topic"
-    )]
-    is_order: String,
+    #[arg(
+        short = 'o',
+        long = "order",
+        required = false,
+        default_value_t = false,
+        help = "order topic"
+    )]
+    is_order: bool,

Then on line 90:

-        let is_order = self.is_order.trim().parse::<bool>().unwrap_or(false);
+        let is_order = self.is_order;

Also applies to: 90-90

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs`
around lines 51 - 58, The is_order field is declared as String but should be a
bool; change the struct field is_order: String to is_order: bool and update the
clap attribute to use a boolean default (e.g., default_value_t = false) so clap
parses it natively, then remove the manual parsing/unwrap_or(false) usage
wherever is_order is later parsed or converted (references: the is_order struct
field and the place that currently calls unwrap_or(false) on it) and use the
bool value directly.

61-75: Simplify format_timestamp using DateTime::from_timestamp_millis.

The manual secs/nanos split is unnecessary; DateTime::from_timestamp_millis accepts milliseconds directly.

♻️ Proposed fix
 fn format_timestamp(timestamp: i64) -> String {
     if timestamp <= 0 {
         return "-".to_string();
     }
-    let secs = timestamp / 1000;
-    let nanos = ((timestamp % 1000) * 1_000_000) as u32;
-    match chrono::DateTime::from_timestamp(secs, nanos) {
+    match chrono::DateTime::from_timestamp_millis(timestamp) {
         Some(dt) => {
             use chrono::Local;
             let local_dt = dt.with_timezone(&Local);
             local_dt.format("%Y-%m-%d %H:%M:%S").to_string()
         }
         None => "-".to_string(),
     }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs`
around lines 61 - 75, Replace the manual seconds/nanoseconds split in
format_timestamp with chrono::DateTime::from_timestamp_millis to parse the i64
milliseconds directly: in the function format_timestamp(timestamp: i64) call
DateTime::from_timestamp_millis(timestamp) and handle the Option result (map to
Local timezone and format or return "-" on None), removing secs/nanos
computation and the old from_timestamp call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs`:
- Line 150: The printed "Diff Total" currently uses
consume_stats_list.total_diff (a server-side global) which still counts rows
filtered out by diff_level; update the output to compute and print a local sum
over only the rows actually displayed: iterate the collection you pass to the
table/rendering (the same filtered list used when diff_level > 0), accumulate
the diff field for those rows into a local variable (e.g., visible_total_diff)
and print that instead of consume_stats_list.total_diff; alternatively, if you
prefer to keep both, print both values with clear labels like "Visible Diff
Total" (visible_total_diff) and "Global Diff Total"
(consume_stats_list.total_diff) so operators can distinguish them.
- Around line 131-144: The current code in the broker consume stats printing
block (using offset_wrapper.get_last_timestamp()) skips printing rows when
last_timestamp <= 0, dropping entries that meet diff >= diff_level; remove the
conditional guard that checks offset_wrapper.get_last_timestamp() > 0 and always
call format_timestamp(offset_wrapper.get_last_timestamp()) and the println block
so rows with last_timestamp == 0 are printed (format_timestamp already returns
"-" for nonpositive timestamps); update the block around println that references
mq.get_topic(), group, mq.get_broker_name(), mq.get_queue_id(),
offset_wrapper.get_broker_offset(), offset_wrapper.get_consumer_offset(), diff,
and last_time accordingly.

---

Nitpick comments:
In `@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/Cargo.toml`:
- Line 50: Remove the direct dependency declaration chrono = "0.4" from
rocketmq-admin-core/Cargo.toml and instead add chrono = "0.4" under the root
Cargo.toml `[workspace.dependencies]`, then update
rocketmq-admin-core/Cargo.toml to consume chrono with `{ workspace = true }`;
reference the chrono package name and the workspace.dependencies section to
locate where to move the version declaration and the
rocketmq-admin-core/Cargo.toml to change the local dependency entry.

In
`@rocketmq-tools/rocketmq-admin/rocketmq-admin-core/src/commands/broker_commands/broker_consume_stats_sub_command.rs`:
- Around line 51-58: The is_order field is declared as String but should be a
bool; change the struct field is_order: String to is_order: bool and update the
clap attribute to use a boolean default (e.g., default_value_t = false) so clap
parses it natively, then remove the manual parsing/unwrap_or(false) usage
wherever is_order is later parsed or converted (references: the is_order struct
field and the place that currently calls unwrap_or(false) on it) and use the
bool value directly.
- Around line 61-75: Replace the manual seconds/nanoseconds split in
format_timestamp with chrono::DateTime::from_timestamp_millis to parse the i64
milliseconds directly: in the function format_timestamp(timestamp: i64) call
DateTime::from_timestamp_millis(timestamp) and handle the Option result (map to
Local timezone and format or return "-" on None), removing secs/nanos
computation and the old from_timestamp call.

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 - All CI checks passed ✅

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 auto merge Difficulty level/Moderate Moderate difficult ISSUE feature🚀 Suggest an idea for this project. ready to review waiting-review waiting review this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature🚀] Implement BrokerConsumeStats command in rocketmq-admin-core

4 participants

Comments