Skip to content

[ISSUE #3454]🚀Add BrokerMetricsConstant struct and organized metrics for RocketMQ monitoring✨ #3455

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 12, 2025

Conversation

mxsm
Copy link
Owner

@mxsm mxsm commented Jun 12, 2025

Which Issue(s) This PR Fixes(Closes)

Fixes #3454

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features
    • Introduced a comprehensive set of broker metric names and labels for improved metrics collection and organization.
    • Added utility functions to easily retrieve and classify metric names and labels by type and category.
  • Tests
    • Implemented unit tests to ensure the accuracy and consistency of metric constants and classification utilities.

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

coderabbitai bot commented Jun 12, 2025

Walkthrough

A new module broker_metrics_constant was added to the RocketMQ broker metrics system, centralizing metric name and label constants, utility functions, and classification enums. Module visibility was updated to allow crate-level access, and a new Rust source file implements the BrokerMetricsConstant struct, grouping and organizing metric constants for monitoring.

Changes

File(s) Change Summary
rocketmq-broker/src/metrics.rs Added pub(crate) mod broker_metrics_constant; changed consumer_attr module visibility to pub(crate).
rocketmq-broker/src/metrics/broker_metrics_constant.rs New file: Defines BrokerMetricsConstant struct, metric/label constants, utility methods, classification enums, tests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant BrokerMetricsConstant
    User->>BrokerMetricsConstant: Call utility method (e.g., get_all_gauge_metrics)
    BrokerMetricsConstant-->>User: Return requested metric names
    User->>BrokerMetricsConstant: Classify metric name (e.g., is_counter_metric)
    BrokerMetricsConstant-->>User: Return classification result
    User->>BrokerMetricsConstant: Retrieve label names
    BrokerMetricsConstant-->>User: Return label names
Loading

Assessment against linked issues

Objective Addressed Explanation
Add BrokerMetricsConstant struct and organize metrics for RocketMQ monitoring (#3454)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

In the warren of code, new metrics now shine,
Constants and labels, all neatly aligned.
Gauges and counters, histograms too,
The broker now measures each thing that you do.
With enums and tests, our metrics are strong—
🐇 RocketMQ hops forward, metrics all along!

✨ 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

This PR introduces a new module to organize broker metrics constants for RocketMQ monitoring and updates the module visibility of consumer attributes.

  • Added a new pub(crate) module "broker_metrics_constant" for broker metrics constants.
  • Changed the module declaration of consumer_attr to pub(crate) to improve accessibility within the crate.
Comments suppressed due to low confidence (1)

rocketmq-broker/src/metrics.rs:17

  • [nitpick] Consider using plural naming if this module is intended to hold multiple constants; for example, 'broker_metrics_constants' might better convey its purpose.
pub(crate) mod broker_metrics_constant;

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

🧹 Nitpick comments (2)
rocketmq-broker/src/metrics/broker_metrics_constant.rs (2)

306-336: MetricCategory::from_metric_name ordering hides the Transaction branch

Because the "messages" check appears before the "commit"/"rollback"/"half" clause,
rocketmq_commit_messages_total is categorised as Message instead of Transaction.
This contradicts the semantic grouping and will surprise users querying dashboards.

If that’s unintended, reorder the match arms:

-            name if name.contains("messages")
-                || name.contains("throughput")
-                || name.contains("message_size") =>
-            {
-                Some(Self::Message)
-            }
+            name if name.contains("commit")
+                || name.contains("rollback")
+                || name.contains("half") =>
+            {
+                Some(Self::Transaction)
+            }
+            name if name.contains("messages")
+                || name.contains("throughput")
+                || name.contains("message_size") =>
+            {
+                Some(Self::Message)
+            }

If you intentionally treat commit/rollback as message metrics (the current unit-test expectation), please add a clarifying comment to avoid future confusion.


189-248: Avoid per-call heap allocations in get_all_* helpers

Each helper currently allocates a fresh Vec.
These are static sets that will never change at runtime; using &'static [&'static str] avoids repeated allocations and enables compile-time guarantees:

-    pub fn get_all_gauge_metrics() -> Vec<&'static str> {
-        vec![ /* … */ ]
-    }
+    pub const fn get_all_gauge_metrics() -> &'static [&'static str] {
+        &[
+            Self::GAUGE_PROCESSOR_WATERMARK,
+            /* … */
+        ]
+    }

The same applies to the counter, histogram and label helpers.
This is a micro-optimisation but also clarifies the immutability of the data.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c7a05d4 and cd8049a.

📒 Files selected for processing (2)
  • rocketmq-broker/src/metrics.rs (1 hunks)
  • rocketmq-broker/src/metrics/broker_metrics_constant.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: build
  • GitHub Check: build (ubuntu-latest, nightly)
  • GitHub Check: test
  • GitHub Check: build (windows-latest, stable)
  • GitHub Check: auto-approve
  • GitHub Check: build (macos-latest, stable)
  • GitHub Check: build (macos-latest, nightly)
  • GitHub Check: build (windows-latest, nightly)
  • GitHub Check: build (ubuntu-latest, stable)
🔇 Additional comments (1)
rocketmq-broker/src/metrics.rs (1)

17-18: Visibility change looks correct

Promoting consumer_attr to pub(crate) and exposing the new broker_metrics_constant module integrates cleanly with the crate hierarchy.
No further action required.

Comment on lines +250 to +269
/// Check if a metric name is a gauge
pub fn is_gauge_metric(metric_name: &str) -> bool {
metric_name.starts_with("rocketmq_")
&& !metric_name.contains("_total")
&& !metric_name.contains("_time")
&& !metric_name.contains("_size")
&& !metric_name.contains("_latency")
}

/// Check if a metric name is a counter
pub fn is_counter_metric(metric_name: &str) -> bool {
metric_name.ends_with("_total")
}

/// Check if a metric name is a histogram
pub fn is_histogram_metric(metric_name: &str) -> bool {
metric_name.contains("_time")
|| metric_name.contains("_size")
|| metric_name.contains("_latency")
}
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

is_gauge_metric / is_histogram_metric mis-classify several declared gauge metrics

is_gauge_metric explicitly rejects names that contain _latency, _size, or _time, while is_histogram_metric treats those substrings as a positive signal.
However, you have six gauges that contain _latency:

rocketmq_consumer_lag_latency
rocketmq_consumer_queueing_latency
rocketmq_finish_message_latency   // in histogram list

Consequences:

  1. is_gauge_metric("rocketmq_consumer_lag_latency")false (should be true).
  2. is_histogram_metric("rocketmq_consumer_lag_latency")true (should be false).
  3. MetricType::from_metric_name therefore yields Histogram for a gauge, breaking downstream logic and any Prom-reg-type registration.

Minimal, allocation-free fix:

-    pub fn is_gauge_metric(metric_name: &str) -> bool {
-        metric_name.starts_with("rocketmq_")
-            && !metric_name.contains("_total")
-            && !metric_name.contains("_time")
-            && !metric_name.contains("_size")
-            && !metric_name.contains("_latency")
-    }
-
-    pub fn is_histogram_metric(metric_name: &str) -> bool {
-        metric_name.contains("_time")
-            || metric_name.contains("_size")
-            || metric_name.contains("_latency")
-    }
+    pub fn is_gauge_metric(metric_name: &str) -> bool {
+        Self::get_all_gauge_metrics().iter().any(|m| *m == metric_name)
+    }
+
+    pub fn is_histogram_metric(metric_name: &str) -> bool {
+        Self::get_all_histogram_metrics().iter().any(|m| *m == metric_name)
+    }

This leverages the authoritative constant lists, eliminating heuristic drift.
Please update the related unit tests to cover the latency-suffixed gauges so the issue can’t regress.

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

🤖 Prompt for AI Agents
In rocketmq-broker/src/metrics/broker_metrics_constant.rs around lines 250 to
269, the functions is_gauge_metric and is_histogram_metric incorrectly classify
metrics containing "_latency" by using substring heuristics that conflict with
the actual gauge metrics list. To fix this, replace the heuristic checks with
lookups against authoritative constant lists of gauge and histogram metric names
to ensure accurate classification without allocations. Also, update or add unit
tests to cover latency-suffixed gauge metrics like
"rocketmq_consumer_lag_latency" to prevent future regressions.

Copy link

codecov bot commented Jun 12, 2025

Codecov Report

Attention: Patch coverage is 97.80220% with 4 lines in your changes missing coverage. Please review.

Project coverage is 26.25%. Comparing base (c7a05d4) to head (cd8049a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...etmq-broker/src/metrics/broker_metrics_constant.rs 97.80% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3455      +/-   ##
==========================================
+ Coverage   26.09%   26.25%   +0.16%     
==========================================
  Files         543      544       +1     
  Lines       77329    77511     +182     
==========================================
+ Hits        20176    20354     +178     
- Misses      57153    57157       +4     

☔ 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 2db3f34 into main Jun 12, 2025
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 12, 2025
@mxsm mxsm deleted the feature-3454 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 feature🚀 Suggest an idea for this project.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature🚀] Add BrokerMetricsConstant struct and organized metrics for RocketMQ monitoring
3 participants