Skip to content

Conversation

@huangdijia
Copy link
Contributor

@huangdijia huangdijia commented Dec 1, 2025

Summary

  • Add configurable default metrics collection via SENTRY_ENABLE_DEFAULT_METRICS environment variable
  • Extend metrics collection to command-line operations with Timer-based periodic collection
  • Add worker identification tags to memory metrics for better monitoring
  • Separate default metrics control from general metrics enablement

Changes Made

  • Configuration: Added SENTRY_ENABLE_DEFAULT_METRICS environment variable support
  • Feature Class: New isDefaultMetricsEnabled() method for granular control
  • Command Metrics: Extended OnBeforeHandle listener to collect comprehensive command-line metrics
  • Worker Tags: Added worker identification to memory usage metrics
  • Periodic Collection: Implemented Timer-based metrics collection for long-running commands
  • Resource Monitoring: Added garbage collection and system resource usage tracking

Test plan

  • Verify default metrics can be enabled/disabled via configuration
  • Test command-line metrics collection with various commands
  • Confirm worker tags appear correctly in memory metrics
  • Validate periodic metrics collection during long-running commands
  • Ensure backward compatibility with existing metrics configuration
  • Check that custom metrics still work independently of default metrics

Summary by CodeRabbit

  • 新功能
    • 添加独立配置项:启用/禁用“默认指标”和“命令指标”,可单独控制两类指标收集。
  • 改进
    • 指标收集按新开关调整:命令执行期间可按需启动周期性采集并在工作线程中运行与清理。
    • 内存相关指标增加工作线程标签以提升区分度。
    • 将运行标识由编译时常量改为运行时可变属性以支持动态控制。

✏️ Tip: You can customize this high-level summary in your review settings.

…tion

- Add SENTRY_ENABLE_DEFAULT_METRICS configuration option
- Implement isDefaultMetricsEnabled() method in Feature class
- Extend OnBeforeHandle listener to collect command-line metrics
- Add worker identification tags to memory metrics
- Separate default metrics from custom metrics collection
- Add Timer-based periodic metrics collection for commands
- Include garbage collection and resource usage metrics

This enhancement provides more granular control over metrics collection
and extends monitoring capabilities to command-line operations.
@coderabbitai
Copy link

coderabbitai bot commented Dec 1, 2025

Warning

Rate limit exceeded

@huangdijia has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between bdc47ab and ac2f7eb.

📒 Files selected for processing (2)
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php (1 hunks)
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php (3 hunks)

Walkthrough

添加两个公开配置键 enable_default_metricsenable_command_metrics(默认 true);将其列入 ClientBuilderFactory 的 SPECIFIC_OPTIONS;在 Feature 中新增对应查询方法;并在多个指标监听器中以这些新标志调整指标采集门控与 OnBeforeHandle 的定时器/生命周期逻辑(工作进程定时采集与清理)。

Changes

内聚体 / 文件(s) 变更摘要
配置
src/sentry/publish/sentry.php
新增公开配置键 enable_default_metricsenable_command_metrics,均以 env(..., true) 为默认值。
工厂
src/sentry/src/Factory/ClientBuilderFactory.php
'enable_default_metrics''enable_command_metrics' 添加到 SPECIFIC_OPTIONS 常量,以在合并前将其从用户配置中移除。
Feature 功能检测
src/sentry/src/Feature.php
新增方法 isDefaultMetricsEnabled(bool $default = true): boolisCommandMetricsEnabled(bool $default = true): bool;若整体 metrics 被禁用则短路返回 false,否则读取对应配置。
OnBeforeHandle 监听器
src/sentry/src/Metrics/Listener/OnBeforeHandle.php
引入 MetricSetter trait、添加 Timer 属性与构造器注入 Feature;重构 BeforeHandle/AfterExecute 流程,按命令指标标志启用定时器周期性采集(memory、GC、getrusage 等),并在 worker 退出时清理定时器与刷新指标。
OnCoroutineServerStart 监听器
src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php
在派发 MetricFactoryReady 后若 isDefaultMetricsEnabled() 为 false 则提前返回以跳过默认指标采集;内存相关指标附加 ['worker' => '0'] 标签。
OnMetricFactoryReady 监听器
src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
将早期返回判断由 isMetricsEnabled() 改为 isDefaultMetricsEnabled(),并用 Constants::$runningInCommand 替代常量上下文读取以判断命令模式。
OnWorkerStart 监听器
src/sentry/src/Metrics/Listener/OnWorkerStart.php
将条件判断由 isMetricsEnabled() 切换为 isDefaultMetricsEnabled(),其余初始化与派发逻辑保持不变。
MetricSetter trait
src/sentry/src/Metrics/Traits/MetricSetter.php
添加注释占位符方法 spawnDefaultMetrics(仅注释,无运行时代码)。
常量
src/sentry/src/Constants.php
移除常量 RUN_IN_COMMAND,新增公有静态布尔属性 public static bool $runningInCommand = false; 以在运行时标记命令模式。

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant OnBeforeHandle
    participant Timer
    participant MetricSetter
    participant MetricsBackend

    Worker->>OnBeforeHandle: BeforeHandle 事件
    OnBeforeHandle->>OnBeforeHandle: 设置运行中命令标记
    alt enable_command_metrics == true
        OnBeforeHandle->>Timer: 启动/注册周期 tick 回调
        Timer->>MetricSetter: 周期触发采集
        MetricSetter->>MetricsBackend: 收集并上报指标 (memory/gc/ru...)
        MetricsBackend-->>MetricSetter: 确认或缓存
        OnBeforeHandle->>Worker: 注册退出时刷新/清理动作
    end
    Worker->>OnBeforeHandle: AfterExecute 事件
    OnBeforeHandle->>OnBeforeHandle: 清理命令标记与停止 Timer(如存在)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • 重点审查 src/sentry/src/Metrics/Listener/OnBeforeHandle.php:定时器与协程生命周期(启动/取消/清理)与并发边界、资源泄漏风险。
  • 验证 Constants::$runningInCommand 的运行时语义替换常量的影响及线程/协程可见性。
  • 检查 ClientBuilderFactory::SPECIFIC_OPTIONS 的变更不会在配置合并时遗漏或错误移除其他关键选项。

Possibly related PRs

庆贺诗

🐰 我在菜地数跳动,定时器里数心跳,

默认与命令分两道,采集轻盈不喧嚣。
退出时一跳清理好,胡萝卜香里做分享。 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 标题清晰准确地概括了主要变更内容:添加可配置的默认指标收集功能。标题与变更集的核心目标高度相关,涵盖了PR的主要功能增强。

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

@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 (2)
src/sentry/src/Metrics/Traits/MetricSetter.php (1)

34-37: 移除无用的注释占位代码。

注释掉的 spawnDefaultMetrics 方法没有实际用途,会增加代码维护负担。如果有未来计划,建议用 TODO 注释说明,否则请移除。

-
-    // protected function spawnDefaultMetrics()
-    // {
-    // }
src/sentry/publish/sentry.php (1)

45-45: 建议添加文档注释。

其他配置项如 enable_metrics 都有 @see 注释链接到文档,建议为 enable_default_metrics 也添加相应说明,便于用户理解其用途。

     // @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#enable_metrics
     'enable_metrics' => env('SENTRY_ENABLE_METRICS', true),
+    // Controls default system metrics collection (memory, GC, resource usage)
     'enable_default_metrics' => env('SENTRY_ENABLE_DEFAULT_METRICS', true),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a086c9 and 9716e0e.

📒 Files selected for processing (8)
  • src/sentry/publish/sentry.php (1 hunks)
  • src/sentry/src/Factory/ClientBuilderFactory.php (1 hunks)
  • src/sentry/src/Feature.php (1 hunks)
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php (2 hunks)
  • src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php (2 hunks)
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php (1 hunks)
  • src/sentry/src/Metrics/Listener/OnWorkerStart.php (1 hunks)
  • src/sentry/src/Metrics/Traits/MetricSetter.php (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/*/src/**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

All components use the namespace pattern: FriendsOfHyperf\{ComponentName}

Files:

  • src/sentry/src/Metrics/Traits/MetricSetter.php
  • src/sentry/src/Factory/ClientBuilderFactory.php
  • src/sentry/src/Metrics/Listener/OnWorkerStart.php
  • src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Feature.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.php: Follow PSR-12 coding standards for all PHP code
Use PHP-CS-Fixer for code formatting as configured in .php-cs-fixer.php
Use PHPStan for static analysis as configured in phpstan.neon.dist

Files:

  • src/sentry/src/Metrics/Traits/MetricSetter.php
  • src/sentry/src/Factory/ClientBuilderFactory.php
  • src/sentry/src/Metrics/Listener/OnWorkerStart.php
  • src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Feature.php
  • src/sentry/publish/sentry.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
🧬 Code graph analysis (3)
src/sentry/src/Metrics/Listener/OnWorkerStart.php (2)
src/sentry/src/Function.php (1)
  • feature (25-28)
src/sentry/src/Feature.php (1)
  • isDefaultMetricsEnabled (39-46)
src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php (2)
src/sentry/src/Function.php (2)
  • feature (25-28)
  • metrics (30-33)
src/sentry/src/Feature.php (1)
  • isDefaultMetricsEnabled (39-46)
src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php (2)
src/sentry/src/Function.php (1)
  • feature (25-28)
src/sentry/src/Feature.php (1)
  • isDefaultMetricsEnabled (39-46)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (17)
  • GitHub Check: Test on PHP 8.2 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 6.1.3
🔇 Additional comments (6)
src/sentry/src/Factory/ClientBuilderFactory.php (1)

34-34: LGTM!

新增的 enable_default_metrics 配置项正确地添加到 SPECIFIC_OPTIONS 数组中,确保该选项在合并到 ClientBuilder 之前被移除,与其他框架特定选项的处理方式保持一致。

src/sentry/src/Feature.php (1)

39-46: LGTM!

新方法 isDefaultMetricsEnabled() 实现正确:

  • 首先检查 isMetricsEnabled(),确保基础指标功能已启用
  • 遵循现有方法签名模式,支持默认值参数
  • 逻辑清晰,符合分层控制的设计意图
src/sentry/src/Metrics/Listener/OnWorkerStart.php (1)

56-58: LGTM!

将检查条件从 isMetricsEnabled() 更改为 isDefaultMetricsEnabled() 与 PR 目标一致,实现了默认指标收集的独立控制。

src/sentry/src/Metrics/Listener/OnCoroutineServerStart.php (2)

70-72: LGTM!

正确添加了默认指标启用检查,与其他监听器逻辑保持一致。


112-118: LGTM!

为内存指标添加 worker 标签,与其他指标收集点保持一致。协程服务器使用硬编码 '0' 是合理的,因为它运行在单一 worker 上下文中。

src/sentry/src/Metrics/Listener/OnBeforeHandle.php (1)

63-108: 指标收集逻辑实现良好。

周期性指标收集涵盖了 GC 状态、资源使用情况和内存指标,使用 defer 确保指标刷新,符合 PR 目标中描述的命令行指标收集需求。

Comment on lines 52 to 55
if ($event instanceof AfterExecute) {
Context::destroy(Constants::RUN_IN_COMMAND);
return;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Timer 资源泄漏:命令结束时未清理定时器。

AfterExecute 事件触发时,只是销毁了上下文但没有清理 $timerId。如果命令在 WORKER_EXIT 之前完成,定时器会继续运行直到 worker 退出,造成不必要的资源消耗。

建议保存 timerId 并在 AfterExecute 时清理:

 class OnBeforeHandle implements ListenerInterface
 {
     use MetricSetter;

     protected Timer $timer;

+    protected ?int $timerId = null;
+
     public function __construct(protected Feature $feature)
     {
         $this->timer = new Timer();
     }
     public function process(object $event): void
     {
         if ($event instanceof AfterExecute) {
+            if ($this->timerId !== null) {
+                $this->timer->clear($this->timerId);
+                $this->timerId = null;
+            }
             Context::destroy(Constants::RUN_IN_COMMAND);
             return;
         }
-        $timerId = $this->timer->tick($this->feature->getMetricsInterval(), function () use ($metrics) {
+        $this->timerId = $this->timer->tick($this->feature->getMetricsInterval(), function () use ($metrics) {
-        Coroutine::create(function () use ($timerId) {
+        Coroutine::create(function () {
             CoordinatorManager::until(\Hyperf\Coordinator\Constants::WORKER_EXIT)->yield();
-            $this->timer->clear($timerId);
+            if ($this->timerId !== null) {
+                $this->timer->clear($this->timerId);
+                $this->timerId = null;
+            }
         });

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

🤖 Prompt for AI Agents
In src/sentry/src/Metrics/Listener/OnBeforeHandle.php around lines 52-55, the
AfterExecute branch destroys the context but does not clear the active timer,
leaking the timer until worker exit; capture and store the timer ID when
creating the timer (e.g. as a private property on the listener or in Context),
and in the AfterExecute handler call the appropriate clear function
(clearTimer/Timer::clear/pcntl_alarm/ev_timer_clear depending on implementation)
using that stored timerId before destroying the context so the timer is
cancelled immediately when the command finishes.

Copy link

@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

♻️ Duplicate comments (1)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (1)

52-55: Timer 资源泄漏问题已在之前的审查中指出。

此问题已在之前的审查评论中详细说明:当 AfterExecute 事件触发时,仅销毁了上下文但未清理定时器。请参考之前的审查建议,将 timerId 存储为类属性,并在 AfterExecute 时清理。

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9716e0e and f4a613a.

📒 Files selected for processing (4)
  • src/sentry/publish/sentry.php (1 hunks)
  • src/sentry/src/Factory/ClientBuilderFactory.php (1 hunks)
  • src/sentry/src/Feature.php (1 hunks)
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/sentry/publish/sentry.php
  • src/sentry/src/Feature.php
🧰 Additional context used
📓 Path-based instructions (2)
src/*/src/**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

All components use the namespace pattern: FriendsOfHyperf\{ComponentName}

Files:

  • src/sentry/src/Factory/ClientBuilderFactory.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.php: Follow PSR-12 coding standards for all PHP code
Use PHP-CS-Fixer for code formatting as configured in .php-cs-fixer.php
Use PHPStan for static analysis as configured in phpstan.neon.dist

Files:

  • src/sentry/src/Factory/ClientBuilderFactory.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
🧬 Code graph analysis (1)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (1)
src/sentry/src/Metrics/Traits/MetricSetter.php (1)
  • trySet (20-33)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (15)
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
🔇 Additional comments (3)
src/sentry/src/Factory/ClientBuilderFactory.php (1)

34-35: LGTM!

新增的 enable_default_metricsenable_command_metrics 配置项正确添加到 SPECIFIC_OPTIONS 常量中,确保这些选项在合并用户配置前被正确处理。与 metrics_interval 放在一起,逻辑分组清晰。

src/sentry/src/Metrics/Listener/OnBeforeHandle.php (2)

15-37: 导入和类结构设计合理。

新增的依赖注入(Feature)和 Timer 属性初始化遵循良好的设计模式。使用 MetricSetter trait 复用指标设置逻辑是正确的做法。


110-113: WORKER_EXIT 清理逻辑正确。

使用协程等待 WORKER_EXIT 信号来清理定时器是正确的模式,确保在 worker 退出时资源被释放。结合之前评论中建议的 AfterExecute 清理,可以形成完整的资源管理策略。

Copy link

@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

♻️ Duplicate comments (2)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (2)

51-54: 严重:命令结束时未清理定时器导致资源泄漏。

AfterExecute 事件触发时,只是将 $runningInCommand 标志设为 false,但没有清理在 BeforeHandle 中启动的定时器(第 89 行)。如果命令在 worker 退出前完成,定时器会持续运行直到 worker 退出,造成:

  1. 不必要的资源消耗(定期执行回调)
  2. 可能采集到错误的指标数据(命令已结束但仍在采集)

建议保存定时器 ID 并在 AfterExecute 时清理:

 class OnBeforeHandle implements ListenerInterface
 {
     use MetricSetter;

     protected Timer $timer;
+    protected ?int $timerId = null;

     public function __construct(protected Feature $feature)
     {
         $this->timer = new Timer();
     }
     public function process(object $event): void
     {
         if ($event instanceof AfterExecute) {
+            if ($this->timerId !== null) {
+                $this->timer->clear($this->timerId);
+                $this->timerId = null;
+            }
             Constants::$runningInCommand = false;
             return;
         }
-        $timerId = $this->timer->tick($this->feature->getMetricsInterval(), function () use ($metrics) {
+        $this->timerId = $this->timer->tick($this->feature->getMetricsInterval(), function () use ($metrics) {
-        Coroutine::create(function () use ($timerId) {
+        Coroutine::create(function () {
             CoordinatorManager::until(\Hyperf\Coordinator\Constants::WORKER_EXIT)->yield();
-            $this->timer->clear($timerId);
+            if ($this->timerId !== null) {
+                $this->timer->clear($this->timerId);
+                $this->timerId = null;
+            }
         });

89-107: Worker 标签不一致。

在定时器回调中,trySet() 调用使用默认参数 workerId=0(参见 MetricSetter trait 定义),导致 gc_*ru_* 指标的 worker 标签为 '0',而显式的 gauge() 调用使用 'N/A'。在命令行上下文中,所有指标应使用一致的 worker 标识符。

建议统一使用相同的标识符,例如:

方案 1:统一使用 'N/A'(如果 trySet() 支持字符串类型)

-            $this->trySet('gc_', $metrics, gc_status());
-            $this->trySet('', $metrics, getrusage());
+            $this->trySet('gc_', $metrics, gc_status(), 'N/A');
+            $this->trySet('', $metrics, getrusage(), 'N/A');

方案 2:统一使用 -1

-            $this->trySet('gc_', $metrics, gc_status());
-            $this->trySet('', $metrics, getrusage());
+            $this->trySet('gc_', $metrics, gc_status(), -1);
+            $this->trySet('', $metrics, getrusage(), -1);
             
             metrics()->gauge(
                 'memory_usage',
                 (float) memory_get_usage(),
-                ['worker' => 'N/A'],
+                ['worker' => '-1'],
                 Unit::byte()
             );
             metrics()->gauge(
                 'memory_peak_usage',
                 (float) memory_get_peak_usage(),
-                ['worker' => 'N/A'],
+                ['worker' => '-1'],
                 Unit::byte()
             );

推荐使用方案 2,保持类型一致性(整数转字符串标签)。

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f4a613a and bdc47ab.

📒 Files selected for processing (3)
  • src/sentry/src/Constants.php (1 hunks)
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php (2 hunks)
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
🧰 Additional context used
📓 Path-based instructions (2)
src/*/src/**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

All components use the namespace pattern: FriendsOfHyperf\{ComponentName}

Files:

  • src/sentry/src/Constants.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
**/*.php

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.php: Follow PSR-12 coding standards for all PHP code
Use PHP-CS-Fixer for code formatting as configured in .php-cs-fixer.php
Use PHPStan for static analysis as configured in phpstan.neon.dist

Files:

  • src/sentry/src/Constants.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
🧬 Code graph analysis (1)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (5)
src/sentry/src/Feature.php (4)
  • Feature (18-109)
  • __construct (20-22)
  • isCommandMetricsEnabled (48-55)
  • getMetricsInterval (57-66)
src/sentry/src/Metrics/Timer.php (1)
  • Timer (18-62)
src/sentry/src/Function.php (1)
  • metrics (30-33)
src/sentry/src/Constants.php (1)
  • Constants (14-43)
src/sentry/src/Metrics/Traits/MetricSetter.php (1)
  • trySet (20-33)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.1 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 6.0.2
🔇 Additional comments (4)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (4)

15-25: 导入语句正确。

新增的导入项与新增功能需求一致,包括特性标志检查、指标设置、定时器管理和协程调度。


29-31: 特性和属性声明正确。

MetricSetter 特性提供了后续使用的 trySet() 方法,Timer 属性正确声明为 Hyperf 协调器定时器类型。


33-36: 构造函数依赖注入恰当。

通过构造函数注入 Feature 依赖并初始化 Timer,符合依赖注入最佳实践。由于这是事件监听器,通常由容器管理,构造函数签名变更不会影响用户代码。


56-60: 命令指标启用检查正确。

在设置 $runningInCommand 标志后,正确使用特性标志 isCommandMetricsEnabled() 进行门控,避免在未启用时执行不必要的指标收集逻辑。

@huangdijia huangdijia merged commit 1b454df into main Dec 1, 2025
22 checks passed
@huangdijia huangdijia deleted the feat/sentry-default-metrics-enhancement branch December 1, 2025 10:05
huangdijia added a commit that referenced this pull request Dec 1, 2025
…tion (#1034)

* feat: enhance Sentry metrics with configurable default metrics collection

- Add SENTRY_ENABLE_DEFAULT_METRICS configuration option
- Implement isDefaultMetricsEnabled() method in Feature class
- Extend OnBeforeHandle listener to collect command-line metrics
- Add worker identification tags to memory metrics
- Separate default metrics from custom metrics collection
- Add Timer-based periodic metrics collection for commands
- Include garbage collection and resource usage metrics

This enhancement provides more granular control over metrics collection
and extends monitoring capabilities to command-line operations.

* feat: 添加命令指标启用选项并更新相关逻辑

* feat: 使用静态变量替代上下文管理命令运行状态

* feat: 移除AfterExecute事件监听并优化命令指标处理逻辑

* fix: 更新注释以更清晰地说明命令自动退出的条件

* fix: 修复命令指标处理逻辑,确保在适当条件下启用指标收集

* fix: 优化命令指标启用逻辑,确保在适当条件下收集指标

* fix: 修复命令指标启用逻辑,确保在适当条件下收集默认指标

* fix: 更新指标收集逻辑,将工人标识从'N/A'更改为'0'

* fix: 修复默认指标启用逻辑,确保在禁用时正确返回

---------

Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants