Skip to content

Conversation

@huangdijia
Copy link
Contributor

@huangdijia huangdijia commented Dec 22, 2025

Summary

  • Refactored SingletonAspect to use a more efficient match expression for handling different Sentry class types
  • Eliminated complex closure-based singleton instance reset logic in favor of direct instantiation where appropriate
  • Improved performance and code readability while maintaining coroutine safety

Changes

  • Replaced the complex Context::getOrSet closure with a match expression that explicitly handles different Sentry class types
  • Direct instantiation for singleton classes (HubAdapter, IntegrationRegistry, TraceMetrics)
  • Bypass context handling for enum types to improve performance
  • Default fallback to original behavior for unknown classes

Test plan

  • Verify that Sentry singleton instances work correctly in coroutine context
  • Test that enum classes bypass context handling as expected
  • Ensure no regression in existing Sentry functionality
  • Run the test suite to confirm all tests pass

🤖 Generated with Claude Code

Summary by CodeRabbit

发布说明

  • 优化
    • 精简单例管理:仅保留 HubAdapter、IntegrationRegistry、TraceMetrics 为活动单例,其他条目以枚举形式注释以避免被缓存。
    • 调整单例缓存/初始化为基于上下文的获取与闭包创建,简化生命周期处理。
    • 统一将协程延迟执行由 Co::defer 替换为全局 defer,提升协程清理、度量与日志的可靠性。
    • 无外部接口或公开签名变更,兼容性保持。

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

…class handling

Replace the complex closure-based singleton instance reset logic with a more
efficient match expression that explicitly handles different Sentry class types:

- Direct instantiation for singleton classes (HubAdapter, IntegrationRegistry)
- Simplified TraceMetrics creation
- Bypass context handling for enum types
- Default to original behavior for unknown classes

This improves performance, readability, and reduces the overhead of reflection-based
property manipulation while maintaining coroutine safety through Context.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings December 22, 2025 02:26
@coderabbitai
Copy link

coderabbitai bot commented Dec 22, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

将多个文件中对协程延迟执行的调用从 Co::defer 切换为全局函数 defer,并重构单例切面为基于类名的分发处理,使用 Context::getOrSet + 闭包/直接实例化管理若干单例;其余流程保持不变。(≤50 字)

Changes

内聚体 / 文件(s) 变更摘要
单例切面逻辑重构
src/sentry/src/Aspect/SingletonAspect.php
将通用单例重置路径替换为按类名的 match 分发;缩减并注释原有枚举样式单例列表,仅保留 HubAdapterIntegrationRegistryTraceMetrics 为活动项;缓存键检查由 isset($arguments[0]) 变为 !array_key_exists(0, $arguments)(反向判断);对 HubAdapterIntegrationRegistry 使用 Context::getOrSet + 绑定闭包创建/缓存实例,TraceMetrics 使用 Context::getOrSet 直接返回新实例;默认走原有流程,枚举类绕过缓存。
协程 defer 调用统一
src/sentry/src/Aspect/CoroutineAspect.php, src/sentry/src/Tracing/Aspect/CoroutineAspect.php, src/sentry/src/Metrics/Aspect/HistogramAspect.php, src/sentry/src/Metrics/Listener/RequestWatcher.php, src/sentry/src/Tracing/Listener/EventHandleListener.php, src/sentry/src/Tracing/Tracer.php
移除 Hyperf\Engine\Coroutine as Co 别名导入,新增 use function Hyperf\Coroutine\defer;,并将 Co::defer(...) 全部替换为 defer(...);行为与控制流在调用点保持一致,仅更换 defer 的来源与导入方式。

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 分钟

  • 需额外关注点:
    • SingletonAspect 中对 HubAdapterIntegrationRegistry 的闭包绑定(Closure::bind)是否保持原有可见性与初始化语义。
    • 缓存键拼接条件由 isset 反转为 !array_key_exists 后,边界情况(如 null、空字符串、非连续索引参数)语义是否一致。
    • 是否在所有修改处都正确引入 use function Hyperf\Coroutine\defer;,避免命名冲突或缺失。

Possibly related PRs

Suggested reviewers

  • xuanyanwow
  • zds-s

诗歌

🐰 代码园中细步跳,
defer 换身更轻巧;
单例按名躲树杈,闭包悄悄做抱抱,
枚举自去不可撩,
胡萝卜请合并到! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% 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 title accurately captures the main refactoring: optimizing SingletonAspect with match expression. However, the changes also include Co::defer to defer function replacements across multiple files, which is not mentioned in the title.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/singleton-aspect-match-implementation

📜 Recent 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 1423d0c and 384465b.

📒 Files selected for processing (1)
  • src/sentry/src/Aspect/SingletonAspect.php
🧰 Additional context used
📓 Path-based instructions (4)
**/*.php

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

**/*.php: All PHP files must include declare(strict_types=1) at the top
Use PSR-12 coding standards for PHP code formatting
Use 4-space indentation with short array syntax in PHP code
Use .php-cs-fixer.php configuration for PHP code formatting

All PHP files must include a strict_types declaration at the top

**/*.php: Follow project PHP coding standard enforced by php-cs-fixer with PSR-12 style, 4-space indentation, and short array syntax
Maintain type coverage by updating or adding tests when public APIs change; ensure composer test:types stays green before pushing

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/src/**/*.php

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

Use namespace pattern FriendsOfHyperf\{ComponentName} for all component classes

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/*/src/**/*.php

📄 CodeRabbit inference engine (CLAUDE.md)

src/*/src/**/*.php: Namespace convention for components must follow FriendsOfHyperf{ComponentName}
All code must be coroutine-safe and avoid global state without proper context management, blocking I/O operations, and non-coroutine-safe third-party libraries without wrappers
Use Hyperf's Context API for request-scoped data instead of global state
Follows PSR-12 coding standards and use PHP-CS-Fixer for automatic formatting
Use PHPStan at maximum level for static analysis
Ensure component namespace doesn't conflict with existing Hyperf components or other packages in the ecosystem
Integrate deeply with Hyperf's Dependency Injection container for service registration
Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider
Use Hyperf's Event System to register listeners for framework events in components
All code must support coroutine-based concurrency using Swoole/Swow compatibility

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/*.php

📄 CodeRabbit inference engine (AGENTS.md)

Each component lives in its own subdirectory with PSR-4 namespaces matching FriendsOfHyperf\*

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
🧠 Learnings (1)
📚 Learning: 2025-12-12T05:33:43.947Z
Learnt from: CR
Repo: friendsofhyperf/components PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-12T05:33:43.947Z
Learning: Applies to src/*/src/**/*.php : Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider

Applied to files:

  • src/sentry/src/Aspect/SingletonAspect.php
⏰ 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). (18)
  • 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.1 with Swoole 6.0.2
  • 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.3 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.2 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.2 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.1.3
  • GitHub Check: Test on PHP 8.3 with Swoole 6.1.3
  • 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.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
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
🔇 Additional comments (3)
src/sentry/src/Aspect/SingletonAspect.php (3)

21-35: 枚举类注释处理正确,有效提升性能。

将枚举类从 $classes 数组中注释掉是正确的优化。枚举类型是不可变的且线程安全,不需要通过切面进行拦截和上下文管理。这样可以避免不必要的 AOP 调用开销,符合 PR 目标中"为枚举类型绕过上下文处理以提升性能"的描述。


56-66: 默认分支实现正确,确保兼容性。

默认分支通过 $proceedingJoinPoint->process() 保持原始行为,确保了对未明确处理的类的向后兼容性。枚举类的注释与 $classes 数组的修改保持一致。


46-54: 实现方式安全,无需修改。

Sentry SDK 中这三个类的 getInstance() 方法仅包含标准的单例模式检查(if (self::$instance === null) { self::$instance = new self(); }),不含任何额外的初始化逻辑。因此,直接实例化不会跳过任何必要的初始化。Aspect 使用 Context::getOrSet 确保协程安全性,每个协程上下文维护独立的实例,符合编码指南要求。

Likely an incorrect or invalid review comment.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 PHPStan (2.1.33)

At least one path must be specified to analyse.


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

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 attempts to refactor the SingletonAspect to use a match expression instead of the original closure-based approach, claiming to improve performance and readability. However, the refactoring introduces critical bugs that break the singleton pattern implementation for Sentry SDK classes.

Key Issues:

  • Direct class instantiation bypasses the singleton pattern's getInstance() method, breaking initialization logic
  • The argument check logic was inadvertently changed in a way that affects falsy value handling
  • Redundant enum case handling that provides no benefit over the default case

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 (1)
src/sentry/src/Aspect/SingletonAspect.php (1)

55-62: 建议从切面拦截列表中移除枚举类。

第 55-62 行的枚举类(CheckInStatus、EventType、MonitorScheduleUnit 等)直接调用 $proceedingJoinPoint->process(),没有任何特殊处理。然而这些类仍然在 $classes 数组(第 22-32 行)中,导致切面会拦截它们的调用。

根据 PR 目标描述:"bypass context handling for enum types to improve performance",但当前实现仍然拦截了这些枚举类,只是在拦截后直接放行。这会产生不必要的性能开销。

🔎 建议从 $classes 数组中移除枚举类以真正提升性能
     public array $classes = [
-        \Sentry\CheckInStatus::class . '::getInstance',
-        \Sentry\EventType::class . '::getInstance',
-        \Sentry\MonitorScheduleUnit::class . '::getInstance',
         \Sentry\Integration\IntegrationRegistry::class . '::getInstance',
-        \Sentry\Logs\LogLevel::class . '::getInstance',
         \Sentry\Metrics\TraceMetrics::class . '::getInstance',
         \Sentry\State\HubAdapter::class . '::getInstance',
-        \Sentry\Tracing\SpanStatus::class . '::getInstance',
-        \Sentry\Tracing\TransactionSource::class . '::getInstance',
-        \Sentry\Transport\ResultStatus::class . '::getInstance',
-        \Sentry\Unit::class . '::getInstance',
     ];

同时简化 match 表达式:

         return match ($className) {
             // Singleton Classes
             \Sentry\State\HubAdapter::class,
             \Sentry\Integration\IntegrationRegistry::class => Context::getOrSet($key, function () use ($className) {
                 return Closure::bind(fn () => new $className(), null, $className)();
             }),
             \Sentry\Metrics\TraceMetrics::class => Context::getOrSet($key, function () use ($className) {
                 return new $className();
             }),
-
-            // Enums
-            \Sentry\CheckInStatus::class,
-            \Sentry\EventType::class,
-            \Sentry\MonitorScheduleUnit::class,
-            \Sentry\Logs\LogLevel::class,
-            \Sentry\Tracing\SpanStatus::class,
-            \Sentry\Tracing\TransactionSource::class,
-            \Sentry\Transport\ResultStatus::class,
-            \Sentry\Unit::class => $proceedingJoinPoint->process(),
             default => $proceedingJoinPoint->process(),
         };
📜 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 41d8e6e and 450ebcc.

📒 Files selected for processing (1)
  • src/sentry/src/Aspect/SingletonAspect.php
🧰 Additional context used
📓 Path-based instructions (4)
**/*.php

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

**/*.php: All PHP files must include declare(strict_types=1) at the top
Use PSR-12 coding standards for PHP code formatting
Use 4-space indentation with short array syntax in PHP code
Use .php-cs-fixer.php configuration for PHP code formatting

All PHP files must include a strict_types declaration at the top

**/*.php: Follow project PHP coding standard enforced by php-cs-fixer with PSR-12 style, 4-space indentation, and short array syntax
Maintain type coverage by updating or adding tests when public APIs change; ensure composer test:types stays green before pushing

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/src/**/*.php

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

Use namespace pattern FriendsOfHyperf\{ComponentName} for all component classes

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/*/src/**/*.php

📄 CodeRabbit inference engine (CLAUDE.md)

src/*/src/**/*.php: Namespace convention for components must follow FriendsOfHyperf{ComponentName}
All code must be coroutine-safe and avoid global state without proper context management, blocking I/O operations, and non-coroutine-safe third-party libraries without wrappers
Use Hyperf's Context API for request-scoped data instead of global state
Follows PSR-12 coding standards and use PHP-CS-Fixer for automatic formatting
Use PHPStan at maximum level for static analysis
Ensure component namespace doesn't conflict with existing Hyperf components or other packages in the ecosystem
Integrate deeply with Hyperf's Dependency Injection container for service registration
Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider
Use Hyperf's Event System to register listeners for framework events in components
All code must support coroutine-based concurrency using Swoole/Swow compatibility

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/*.php

📄 CodeRabbit inference engine (AGENTS.md)

Each component lives in its own subdirectory with PSR-4 namespaces matching FriendsOfHyperf\*

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
🧠 Learnings (1)
📚 Learning: 2025-12-12T05:33:43.947Z
Learnt from: CR
Repo: friendsofhyperf/components PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-12T05:33:43.947Z
Learning: Applies to src/*/src/**/*.php : Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider

Applied to files:

  • src/sentry/src/Aspect/SingletonAspect.php
⏰ 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). (20)
  • GitHub Check: Test on PHP 8.1 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 5.1.8
  • 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.2 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.2 with Swoole 5.1.8
  • GitHub Check: Test on PHP 8.1 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 6.1.3
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 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.1.3
  • GitHub Check: Agent
  • GitHub Check: Seer Code Review
🔇 Additional comments (1)
src/sentry/src/Aspect/SingletonAspect.php (1)

44-64: 使用 match 表达式提升代码可读性。

使用 match 表达式替代之前的逻辑,使代码更清晰、更易维护。针对不同类型的 Sentry 类采用不同的处理策略,同时保持协程安全性。结构清晰,易于扩展。

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

♻️ Duplicate comments (2)
src/sentry/src/Aspect/SingletonAspect.php (2)

40-42: 修复逻辑取反错误,避免数组访问异常。

条件被取反但函数体保持不变,导致逻辑错误:

  • 原代码:if (isset($arguments[0])) → 当参数存在时追加到 key
  • 新代码:if (! array_key_exists(0, $arguments)) → 当参数不存在时尝试追加 $arguments[0]

这会在 $arguments 为空或不包含索引 0 时抛出 "Undefined array key 0" 错误。

🔎 修复条件逻辑
-        if (! array_key_exists(0, $arguments)) {
+        if (array_key_exists(0, $arguments)) {
             $key .= '#' . $arguments[0];
         }

46-52: 调用原始 getInstance() 而非直接实例化,以保持单例模式完整性。

直接实例化绕过了 Sentry SDK 的 getInstance() 方法,存在以下问题:

  1. 跳过了 getInstance() 中的初始化逻辑
  2. 未正确重置 Sentry SDK 内部的单例状态
  3. 破坏了 Sentry SDK 预期的单例行为

正确做法是在 Hyperf Context 中存储实例以确保协程安全,同时重置内部单例状态后调用原始的 getInstance()

🔎 建议的修复方案
-            \Sentry\State\HubAdapter::class,
-            \Sentry\Integration\IntegrationRegistry::class => Context::getOrSet($key, function () use ($className) {
-                return Closure::bind(fn () => new $className(), null, $className)();
+            \Sentry\State\HubAdapter::class,
+            \Sentry\Integration\IntegrationRegistry::class => Context::getOrSet($key, function () use ($className, $proceedingJoinPoint) {
+                // 重置内部单例状态后调用原始 getInstance()
+                Closure::bind(static function () {
+                    self::$instance = null;
+                }, null, $className)();
+                
+                return $proceedingJoinPoint->process();
             }),
-            \Sentry\Metrics\TraceMetrics::class => Context::getOrSet($key, function () use ($className) {
-                return new $className();
+            \Sentry\Metrics\TraceMetrics::class => Context::getOrSet($key, function () use ($className, $proceedingJoinPoint) {
+                // 重置内部单例状态后调用原始 getInstance()
+                Closure::bind(static function () {
+                    self::$instance = null;
+                }, null, $className)();
+                
+                return $proceedingJoinPoint->process();
             }),
🧹 Nitpick comments (1)
src/sentry/src/Aspect/SingletonAspect.php (1)

55-62: 从 $classes 数组中移除枚举类以实现真正的性能优化。

枚举类在 match 表达式中仅调用 $proceedingJoinPoint->process(),与 default 分支行为完全相同。但它们仍在第 22-32 行的 $classes 数组中,这意味着:

  1. 每次枚举调用 getInstance() 仍会触发切面拦截
  2. 产生不必要的切面调用开销
  3. PR 目标中提到的"为枚举类型绕过上下文处理以提升性能"并未实现

建议将以下枚举类从 $classes 数组中移除,让它们完全不经过切面拦截:

  • \Sentry\CheckInStatus::class
  • \Sentry\EventType::class
  • \Sentry\MonitorScheduleUnit::class
  • \Sentry\Logs\LogLevel::class
  • \Sentry\Tracing\SpanStatus::class
  • \Sentry\Tracing\TransactionSource::class
  • \Sentry\Transport\ResultStatus::class
  • \Sentry\Unit::class

枚举是不可变的,不需要协程安全的上下文处理。

🔎 建议的重构方案

$classes 数组中移除枚举类(保留单例类):

     public array $classes = [
-        \Sentry\CheckInStatus::class . '::getInstance',
-        \Sentry\EventType::class . '::getInstance',
-        \Sentry\MonitorScheduleUnit::class . '::getInstance',
         \Sentry\Integration\IntegrationRegistry::class . '::getInstance',
-        \Sentry\Logs\LogLevel::class . '::getInstance',
         \Sentry\Metrics\TraceMetrics::class . '::getInstance',
         \Sentry\State\HubAdapter::class . '::getInstance',
-        \Sentry\Tracing\SpanStatus::class . '::getInstance',
-        \Sentry\Tracing\TransactionSource::class . '::getInstance',
-        \Sentry\Transport\ResultStatus::class . '::getInstance',
-        \Sentry\Unit::class . '::getInstance',
     ];

然后从 match 表达式中移除枚举分支:

         return match ($className) {
             // Singleton Classes
             \Sentry\State\HubAdapter::class,
             \Sentry\Integration\IntegrationRegistry::class => Context::getOrSet($key, function () use ($className) {
                 return Closure::bind(fn () => new $className(), null, $className)();
             }),
             \Sentry\Metrics\TraceMetrics::class => Context::getOrSet($key, function () use ($className) {
                 return new $className();
             }),
-
-            // Enums
-            \Sentry\CheckInStatus::class,
-            \Sentry\EventType::class,
-            \Sentry\MonitorScheduleUnit::class,
-            \Sentry\Logs\LogLevel::class,
-            \Sentry\Tracing\SpanStatus::class,
-            \Sentry\Tracing\TransactionSource::class,
-            \Sentry\Transport\ResultStatus::class,
-            \Sentry\Unit::class => $proceedingJoinPoint->process(),
             default => $proceedingJoinPoint->process(),
         };
📜 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 ff15010 and 1423d0c.

📒 Files selected for processing (1)
  • src/sentry/src/Aspect/SingletonAspect.php
🧰 Additional context used
📓 Path-based instructions (4)
**/*.php

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

**/*.php: All PHP files must include declare(strict_types=1) at the top
Use PSR-12 coding standards for PHP code formatting
Use 4-space indentation with short array syntax in PHP code
Use .php-cs-fixer.php configuration for PHP code formatting

All PHP files must include a strict_types declaration at the top

**/*.php: Follow project PHP coding standard enforced by php-cs-fixer with PSR-12 style, 4-space indentation, and short array syntax
Maintain type coverage by updating or adding tests when public APIs change; ensure composer test:types stays green before pushing

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/src/**/*.php

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

Use namespace pattern FriendsOfHyperf\{ComponentName} for all component classes

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/*/src/**/*.php

📄 CodeRabbit inference engine (CLAUDE.md)

src/*/src/**/*.php: Namespace convention for components must follow FriendsOfHyperf{ComponentName}
All code must be coroutine-safe and avoid global state without proper context management, blocking I/O operations, and non-coroutine-safe third-party libraries without wrappers
Use Hyperf's Context API for request-scoped data instead of global state
Follows PSR-12 coding standards and use PHP-CS-Fixer for automatic formatting
Use PHPStan at maximum level for static analysis
Ensure component namespace doesn't conflict with existing Hyperf components or other packages in the ecosystem
Integrate deeply with Hyperf's Dependency Injection container for service registration
Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider
Use Hyperf's Event System to register listeners for framework events in components
All code must support coroutine-based concurrency using Swoole/Swow compatibility

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
src/**/*.php

📄 CodeRabbit inference engine (AGENTS.md)

Each component lives in its own subdirectory with PSR-4 namespaces matching FriendsOfHyperf\*

Files:

  • src/sentry/src/Aspect/SingletonAspect.php
🧠 Learnings (1)
📚 Learning: 2025-12-12T05:33:43.947Z
Learnt from: CR
Repo: friendsofhyperf/components PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-12T05:33:43.947Z
Learning: Applies to src/*/src/**/*.php : Leverage Hyperf's AOP (Aspect-Oriented Programming) for cross-cutting concerns via aspects defined in ConfigProvider

Applied to files:

  • src/sentry/src/Aspect/SingletonAspect.php
⏰ 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). (19)
  • 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.2 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.2 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.8
  • 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.2 with Swoole 6.1.3
  • GitHub Check: Test on PHP 8.3 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 5.1.8
  • 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.3 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Seer Code Review

$arguments = $proceedingJoinPoint->getArguments();

if (isset($arguments[0])) {
if (! array_key_exists(0, $arguments)) {
Copy link

Choose a reason for hiding this comment

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

Bug: The condition ! array_key_exists(0, $arguments) is the inverse of the previous logic. It incorrectly executes the following block when no arguments are passed, causing an error.
Severity: CRITICAL | Confidence: High

🔍 Detailed Analysis

The logic to check for the existence of arguments in singleton getInstance methods has been inverted. The new condition if (! array_key_exists(0, $arguments)) evaluates to true when no arguments are provided. This causes the code to attempt to access $arguments[0] on an empty array, which will trigger a PHP "undefined array key" warning or error on every call to methods like TraceMetrics::getInstance(). This breaks the intended caching behavior.

💡 Suggested Fix

The conditional logic should be corrected to check for the existence of the argument before attempting to access it. Change if (! array_key_exists(0, $arguments)) to if (array_key_exists(0, $arguments)) to correctly append the argument to the cache key only when it is present.

🤖 Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: src/sentry/src/Aspect/SingletonAspect.php#L42

Potential issue: The logic to check for the existence of arguments in singleton
`getInstance` methods has been inverted. The new condition `if (! array_key_exists(0,
$arguments))` evaluates to `true` when no arguments are provided. This causes the code
to attempt to access `$arguments[0]` on an empty array, which will trigger a PHP
"undefined array key" warning or error on every call to methods like
`TraceMetrics::getInstance()`. This breaks the intended caching behavior.

Did we get this right? 👍 / 👎 to inform future reviews.
Reference ID: 7807594

@huangdijia huangdijia merged commit 5ed605c into main Dec 22, 2025
23 checks passed
@huangdijia huangdijia deleted the refactor/singleton-aspect-match-implementation branch December 22, 2025 04:21
huangdijia added a commit that referenced this pull request Dec 22, 2025
* refactor(sentry): optimize SingletonAspect with match expression for class handling

Replace the complex closure-based singleton instance reset logic with a more
efficient match expression that explicitly handles different Sentry class types:

- Direct instantiation for singleton classes (HubAdapter, IntegrationRegistry)
- Simplified TraceMetrics creation
- Bypass context handling for enum types
- Default to original behavior for unknown classes

This improves performance, readability, and reduces the overhead of reflection-based
property manipulation while maintaining coroutine safety through Context.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(sentry): replace Co::defer with defer function for coroutine handling

* fix(sentry): correct condition check for argument existence in SingletonAspect

* refactor(sentry): clean up SingletonAspect by commenting out unused singleton classes and enums

---------

Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.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