Skip to content

Conversation

@huangdijia
Copy link
Contributor

@huangdijia huangdijia commented Dec 30, 2025

Summary

  • Replace static property $transaction with Hyperf's Context API for storing transaction data
  • Add constant TRANSACTION for context key
  • Improve coroutine isolation in Swoole/Swow environments

Details

This change enhances coroutine safety by using Hyperf's Context API instead of a static property. In a coroutine environment like Swoole/Swow, static properties are shared across all coroutines, which can lead to race conditions and incorrect transaction data being associated with the wrong request.

The Context API provides request-scoped storage that is properly isolated between coroutines.

Changes

  • Integration.php:
    • Replace private static ?string $transaction with public const TRANSACTION = 'sentry.integration.transaction'
    • Update getTransaction() to use Context::get(self::TRANSACTION)
    • Update setTransaction() to use Context::set(self::TRANSACTION, $transaction)
    • Add null safety check in event processing

Test plan

  • Run existing Sentry integration tests
  • Verify transaction data is correctly isolated across concurrent requests
  • Test with both Swoole and Swow runtime environments

Summary by CodeRabbit

发布说明

  • 重构

    • 将事务与运行模式状态从静态存储迁移到上下文管理,提升并发场景下的稳定性与一致性。
  • 改进

    • 在命令行/守护进程场景下的度量收集与分支判定改为基于上下文,改善指标采集可靠性。
  • 弃用

    • 标记旧的运行模式标识为即将废弃,建议迁移到新的上下文接口。

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

Replace static property with Hyperf's Context API for storing
transaction data, ensuring proper coroutine isolation in
Swoole/Swow environments.
Copilot AI review requested due to automatic review settings December 30, 2025 00:26
@coderabbitai
Copy link

coderabbitai bot commented Dec 30, 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

将 Integration 中的事务(transaction)存储从私有静态属性迁移到 Hyperf Context,并新增公共常量 TRANSACTION 作为 Context 键。setupOnce() 仅在 getTransaction() 非空时写回 Context;同时引入 SentryContext 的 running-in-command 上下文读写接口并在相关监听器中替换静态访问。

Changes

Cohort / File(s) 变更说明
Integration — 事务上下文迁移
src/sentry/src/Integration.php
新增公常量 TRANSACTION = 'sentry.integration.transaction';将事务从私有静态属性迁移为使用 Hyperf\Context(Context::get / Context::set);getTransaction()/setTransaction() 改为读写 Context;setupOnce() 中仅在 getTransaction() 非空时才写入;微调 PHPStan 注释形式。
上下文:运行在命令模式标记
src/sentry/src/SentryContext.php
新增常量 CTX_RUNNING_IN_COMMAND;新增 setRunningInCommand(): voidisRunningInCommand(): bool,通过 Context 管理 running-in-command 标识。
Metrics 监听器 — 使用 SentryContext
src/sentry/src/Metrics/Listener/OnBeforeHandle.php, src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
移除对 Constants::$runningInCommand 的直接读写,改为调用 SentryContext::setRunningInCommand()SentryContext::isRunningInCommand();相应地替换导入。控制流判断点迁移到 Context API。
常量文档
src/sentry/src/Constants.php
public static bool $runningInCommand 上添加 deprecation PHPDoc(标记自 v3.1,v3.2 将移除),未改变运行时签名或行为。

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Listener as OnBeforeHandle
    participant SentryContext as SentryContext / Context
    participant Integration as Integration
    participant MetricListener as OnMetricFactoryReady

    rect rgb(240,248,255)
    Note right of Listener: 请求/任务开始
    Listener->>SentryContext: setRunningInCommand(true)     %% 标记命令模式
    end

    rect rgb(248,240,255)
    Note right of Integration: 事务创建/获取
    Integration->>SentryContext: get(TRANSACTION) -> maybe Transaction
    alt transaction exists
        Integration->>SentryContext: set(TRANSACTION, transaction)
    end
    end

    rect rgb(240,255,240)
    Note right of MetricListener: Metric 工厂就绪时
    MetricListener->>SentryContext: isRunningInCommand()?
    alt true
        MetricListener->>MetricListener: 使用 server stats factory (command mode)
    else false
        MetricListener->>MetricListener: 使用默认 server stats factory
    end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • xuanyanwow

Poem

🐰 静态的巢穴轻轻放下,
Context 的草垛迎风摇晃,
事务悄然随协程流浪,
公常量点亮旅途方向,
小耳朵里是代码的歌唱 ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 标题准确反映了主要变更内容——将事务存储从静态属性迁移到Context API。
✨ Finishing touches
  • 📝 Generate docstrings

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 refactoring improves coroutine safety in the Sentry integration by replacing a static property with Hyperf's Context API for storing transaction data. In Swoole/Swow environments, static properties are shared across all coroutines, which can cause race conditions. The Context API provides proper request-scoped isolation.

Key changes:

  • Replace static $transaction property with Context API storage using a constant key
  • Add null safety check in event processing to avoid setting empty transactions
  • Minor code style improvement for PHPStan ignore comment placement

class Integration implements IntegrationInterface
{
private static ?string $transaction = null;
public const TRANSACTION = 'sentry.integration.transaction';
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

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

The constant naming doesn't follow the established pattern in the codebase. Looking at the SentryContext class, all context key constants use a prefix like CTX_ (e.g., CTX_CRON_CHECKIN_ID, CTX_CARRIER). For consistency, this constant should be named CTX_TRANSACTION instead of TRANSACTION, and the value should follow the pattern 'sentry.ctx.transaction' instead of 'sentry.integration.transaction'.

Copilot uses AI. Check for mistakes.
Comment on lines 94 to 102
public static function getTransaction(): ?string
{
return self::$transaction;
return Context::get(self::TRANSACTION);
}

public static function setTransaction(?string $transaction): void
{
self::$transaction = $transaction;
Context::set(self::TRANSACTION, $transaction);
}
Copy link

Copilot AI Dec 30, 2025

Choose a reason for hiding this comment

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

The refactored transaction storage methods lack test coverage. Since the Sentry component already has test files (CarrierTest, FeatureTest, SqlParseTest), consider adding tests to verify that getTransaction() and setTransaction() correctly store and retrieve transaction data from the Context API, and that the transaction data is properly isolated between different coroutines.

Copilot uses AI. Check for mistakes.
…text` with new setter and getter methods, deprecating the old static property.
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

🧹 Nitpick comments (1)
src/sentry/src/SentryContext.php (1)

164-172: 方法实现正确,考虑添加清理方法以保持一致性。

这两个方法正确地使用了 Hyperf Context API,实现了命令运行状态的上下文管理。不过注意到类中其他类似的上下文管理(如 destroyRpcSpanContext() 在第 159-162 行)提供了清理方法,建议考虑为 CTX_RUNNING_IN_COMMAND 也添加一个 destroyRunningInCommand() 方法以保持 API 的一致性。

根据学习记录,对于请求范围的数据使用 Hyperf Context API 而非全局状态是正确的做法。

🔎 可选的清理方法实现
+    public static function destroyRunningInCommand(): void
+    {
+        Context::destroy(self::CTX_RUNNING_IN_COMMAND);
+    }
📜 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 24fff17 and e0c524d.

📒 Files selected for processing (4)
  • src/sentry/src/Constants.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/SentryContext.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/SentryContext.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
  • src/sentry/src/Constants.php
src/**/src/**/*.php

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

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

Files:

  • src/sentry/src/SentryContext.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
  • src/sentry/src/Constants.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/SentryContext.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
  • src/sentry/src/Constants.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/SentryContext.php
  • src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php
  • src/sentry/src/Metrics/Listener/OnBeforeHandle.php
  • src/sentry/src/Constants.php
🧠 Learnings (2)
📓 Common learnings
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 : Use Hyperf's Context API for request-scoped data instead of global state
📚 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 : Use Hyperf's Context API for request-scoped data instead of global state

Applied to files:

  • src/sentry/src/SentryContext.php
🧬 Code graph analysis (2)
src/sentry/src/Metrics/Listener/OnMetricFactoryReady.php (1)
src/sentry/src/SentryContext.php (2)
  • SentryContext (18-173)
  • isRunningInCommand (169-172)
src/sentry/src/Metrics/Listener/OnBeforeHandle.php (1)
src/sentry/src/SentryContext.php (2)
  • SentryContext (18-173)
  • setRunningInCommand (164-167)
⏰ 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 6.1.3
  • GitHub Check: Test on PHP 8.1 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.8
  • 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 6.0.2
  • 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.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.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.1 with Swoole 5.1.8
  • 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: Seer Code Review
🔇 Additional comments (5)
src/sentry/src/SentryContext.php (1)

42-43: 常量定义正确!

常量命名遵循类中的命名约定,使用清晰的语义化名称。

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

19-19: 导入语句正确!

正确导入了 SentryContext 以支持新的上下文 API 调用。


87-87: 成功迁移到 Context API!

从静态属性 SentryConstants::$runningInCommand 迁移到 SentryContext::isRunningInCommand() 是正确的,这改善了协程隔离性。逻辑语义保持不变。

根据学习记录,这符合"对请求范围数据使用 Hyperf Context API 而非全局状态"的最佳实践。

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

61-61: 成功迁移到 Context API!

从直接赋值静态属性 Constants::$runningInCommand = true 改为调用 SentryContext::setRunningInCommand() 是正确的。这确保了命令执行状态在协程上下文中正确隔离,避免了不同协程间的状态污染。

根据学习记录,这符合使用 Hyperf Context API 管理请求范围数据的最佳实践。

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

69-72: 弃用标记正确,所有引用已成功迁移。

代码库中未发现对 Constants::$runningInCommand 的直接引用。已验证所有相关代码已成功迁移到 SentryContext API(setRunningInCommand()isRunningInCommand() 方法)。弃用声明的版本信息清晰(v3.1 弃用,v3.2 移除),迁移工作已完成。

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