Skip to content

[ISSUE #3456]🚀Add PopMetricsConstant struct and organized metrics for RocketMQ Pop operations✨ #3457

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 #3456

Brief Description

How Did You Test This Change?

Summary by CodeRabbit

  • New Features
    • Introduced comprehensive constants, enums, and utility functions for Pop (Pull-on-Push) metrics, enhancing metrics collection and categorization for RocketMQ brokers.
    • Added builder utilities for constructing Pop metric labels with support for various label types and values.
  • Tests
    • Included extensive unit tests to validate metric constants, utility functions, enums, and label construction.

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

coderabbitai bot commented Jun 12, 2025

Walkthrough

A new module, pop_metrics_constant, has been introduced to the RocketMQ broker metrics system. This module defines the PopMetricsConstant struct, related enums, label builders, and utility functions to organize and manage all Pop (Pull-on-Push) metrics, including constants, types, and label handling, along with comprehensive unit tests.

Changes

File(s) Change Summary
rocketmq-broker/src/metrics.rs Declared new crate-private module pop_metrics_constant.
rocketmq-broker/src/metrics/pop_metrics_constant.rs Added new module with PopMetricsConstant struct, enums, label builder, utility functions, and tests.

Sequence Diagram(s)

sequenceDiagram
    participant Broker as Broker
    participant PopMetricsConstant as PopMetricsConstant
    participant MetricsSystem as Metrics System

    Broker->>PopMetricsConstant: Retrieve metric/label constants
    Broker->>PopMetricsConstant: Use utility functions to classify metrics
    Broker->>PopMetricsConstant: Build labels with PopMetricLabels
    Broker->>MetricsSystem: Register or update Pop metrics with names/labels
Loading

Assessment against linked issues

Objective Addressed Explanation
Add PopMetricsConstant struct and organized metrics for RocketMQ Pop operations (#3456)

Poem

In the land where metrics hop and play,
PopMetricsConstant now leads the way!
With enums and labels, so tidy and neat,
RocketMQ’s Pop stats are now a treat.
Tests abound, structure profound—
This bunny’s metrics truly astound! 🐇📊

✨ 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 pop_metrics_constant module to centralize constants for RocketMQ Pop operation metrics.

  • Added pop_metrics_constant to the broker metrics registry.
Comments suppressed due to low confidence (1)

rocketmq-broker/src/metrics.rs:19

  • [nitpick] Consider adding a module-level doc comment in pop_metrics_constant.rs to describe its purpose and usage, consistent with other metric modules.
pub(crate) mod pop_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: 3

🧹 Nitpick comments (3)
rocketmq-broker/src/metrics.rs (1)

19-19: Add a brief module-level docstring.

Every sub-module exposed here already carries a one-liner comment except the new pop_metrics_constant; adding the same will keep the public API list self-documented.

rocketmq-broker/src/metrics/pop_metrics_constant.rs (2)

124-130: get_all_metrics() may contain duplicates.

If a constant is accidentally listed in two of the subgroup helpers, duplicates will appear.
Returning a HashSet<&'static str> (or deduplicating with Vec::sort_unstable + dedup) guards against this with negligible cost.


301-327: Label vector order is non-deterministic.

Prometheus client libraries don’t rely on order, but caching layers sometimes do.
Using a BTreeMap internally or sorting before return guarantees stable ordering:

-        labels
+        labels.sort_by(|a, b| a.0.cmp(&b.0));
+        labels
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2db3f34 and 6117e11.

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

186-196: Category detection order can hide the Performance class.

Because the buffer check precedes time_consume, a metric such as
rocketmq_pop_buffer_scan_time_consume is categorised as Buffer, never Performance.
Is that intentional? If not, swap the two contains checks or use a more explicit mapping table.

Comment on lines +255 to +266
impl From<&str> for PutStatus {
fn from(s: &str) -> Self {
match s.to_lowercase().as_str() {
"put_ok" => Self::PutOk,
"create_mapped_file_failed" => Self::CreateMappedFileFailed,
"message_illegal" => Self::MessageIllegal,
"properties_length_too_long" => Self::PropertiesLengthTooLong,
"service_not_available" => Self::ServiceNotAvailable,
"os_page_cache_busy" => Self::OsPageCacheBusy,
_ => Self::UnknownError,
}
}
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

Same fallback issue for PutStatus.

UnknownError becomes a catch-all; callers cannot distinguish “real unknown error” from “bad input”.
Adopt TryFrom/Option as suggested for ReviveMessageType.

🤖 Prompt for AI Agents
In rocketmq-broker/src/metrics/pop_metrics_constant.rs around lines 255 to 266,
the From<&str> implementation for PutStatus uses a catch-all UnknownError for
any unrecognized input, which prevents callers from distinguishing between
actual unknown errors and invalid inputs. Change the implementation to use
TryFrom<&str> returning a Result or Option, so that invalid inputs can be
explicitly handled without conflating them with genuine unknown errors.

Comment on lines +132 to +152
/// Check if a metric name is a Pop-related metric
pub fn is_pop_metric(metric_name: &str) -> bool {
metric_name.starts_with("rocketmq_pop_")
}

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

/// Check if a metric name is a Pop gauge
pub fn is_pop_gauge_metric(metric_name: &str) -> bool {
Self::is_pop_metric(metric_name)
&& !metric_name.ends_with("_total")
&& !metric_name.contains("_time_consume")
}

/// Check if a metric name is a Pop histogram
pub fn is_pop_histogram_metric(metric_name: &str) -> bool {
Self::is_pop_metric(metric_name) && metric_name.contains("_time_consume")
}
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

Heuristic may misclassify future metrics.

is_pop_gauge_metric tags every name that is not _total and not _time_consume as a gauge.
A future counter such as rocketmq_pop_revive_failure_count (no _total) or another histogram without _time_consume would be reported as a gauge.

Consider a whitelist/lookup generated from get_all_*_metrics() instead of suffix heuristics to avoid silent mis-categorisation.

🤖 Prompt for AI Agents
In rocketmq-broker/src/metrics/pop_metrics_constant.rs around lines 132 to 152,
the current heuristic in is_pop_gauge_metric uses suffix and substring checks
that may misclassify future metrics without expected suffixes. To fix this,
replace the heuristic logic with a whitelist or lookup approach by generating
sets of known metric names from get_all_*_metrics() functions and checking
membership in those sets to accurately categorize metrics and avoid silent
misclassification.

Comment on lines +217 to +226
impl From<&str> for ReviveMessageType {
fn from(s: &str) -> Self {
match s.to_lowercase().as_str() {
"normal" => Self::Normal,
"retry" => Self::Retry,
"dlq" => Self::Dlq,
_ => Self::Normal,
}
}
}
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

From<&str> silently falls back to Normal.

Returning a valid enum for unknown input risks masking bad label values.
Prefer:

-impl From<&str> for ReviveMessageType {
-    fn from(s: &str) -> Self {
+impl TryFrom<&str> for ReviveMessageType {
+    type Error = ();
+    fn try_from(s: &str) -> Result<Self, Self::Error> {

and propagate the error, or at least return None via Option.

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

🤖 Prompt for AI Agents
In rocketmq-broker/src/metrics/pop_metrics_constant.rs around lines 217 to 226,
the From<&str> implementation for ReviveMessageType silently defaults to Normal
for unknown strings, which can mask invalid inputs. Change the implementation to
return a Result or Option instead of From, so that invalid strings produce an
error or None. This involves replacing the From trait with a TryFrom or a custom
parsing function that returns Result<Self, Error> or Option<Self>, and handling
unknown inputs explicitly without defaulting to Normal.

Copy link

codecov bot commented Jun 12, 2025

Codecov Report

Attention: Patch coverage is 96.21849% with 9 lines in your changes missing coverage. Please review.

Project coverage is 26.47%. Comparing base (2db3f34) to head (6117e11).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ocketmq-broker/src/metrics/pop_metrics_constant.rs 96.21% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3457      +/-   ##
==========================================
+ Coverage   26.25%   26.47%   +0.21%     
==========================================
  Files         544      545       +1     
  Lines       77511    77749     +238     
==========================================
+ Hits        20354    20583     +229     
- Misses      57157    57166       +9     

☔ 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 deb1ad8 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-3456 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 PopMetricsConstant struct and organized metrics for RocketMQ Pop operations
3 participants