Skip to content

Conversation

@huangdijia
Copy link
Contributor

@huangdijia huangdijia commented Sep 25, 2025

Summary

  • Centralized coroutine ID handling in the Tracer class to improve consistency and reduce code duplication
  • Removed duplicate coroutine.id data setting from individual tracing aspects
  • Added default transaction metadata (status, source, start timestamp) initialization in Tracer
  • Cleaned up unused Coroutine imports from aspect files
  • Improved overall maintainability by consolidating coroutine ID logic

Changes

Core Changes

  • Tracer.php: Added centralized coroutine ID handling for both transactions and spans
  • Tracer.php: Added default metadata initialization for transactions (status, source, start timestamp)

Aspect Files Updated

  • Removed coroutine.id data setting from all tracing aspects:
    • AmqpProducerAspect.php
    • AsyncQueueJobMessageAspect.php
    • CacheAspect.php
    • CoordinatorAspect.php
    • CoroutineAspect.php
    • DbAspect.php
    • ElasticsearchAspect.php
    • FilesystemAspect.php
    • GrpcAspect.php
    • GuzzleHttpClientAspect.php
    • KafkaProducerAspect.php
    • RedisAspect.php
    • RpcAspect.php
    • TraceAnnotationAspect.php

Event Listener Updates

  • EventHandleListener.php: Removed duplicate coroutine ID data and unused source/data settings

Benefits

  1. Consistency: All transactions and spans now consistently include coroutine IDs
  2. DRY Principle: Eliminates code duplication across multiple aspect files
  3. Maintainability: Single point of control for coroutine ID handling
  4. Future-proof: Makes it easier to modify coroutine handling logic in the future

Test Plan

  • Verify all existing tracing functionality continues to work
  • Confirm coroutine IDs are still present in trace data
  • Test various traced operations (DB, Redis, HTTP, etc.)
  • Validate transaction metadata is properly set

Summary by CodeRabbit

  • 新功能
    • 事务与跟踪自动填充默认值(开始时间、状态、来源),统一在事务/跟踪层记录协程上下文。
    • Kafka 批量发布新增 message.count 指标,便于统计批量大小。
  • 重构
    • 移除多处集成中的协程 ID 元数据(数据库、缓存、RPC、HTTP、消息队列、文件系统等),减少噪声并提升数据一致性。
    • 精简事件监听中的来源设置与逐 Span 协程标记,降低冗余。
  • 其他
    • 无破坏性变更;对外接口保持不变。

- Remove duplicate coroutine.id data from individual tracing aspects
- Centralize coroutine ID handling in Tracer class for consistency
- Add default transaction metadata (status, source, start timestamp) in Tracer
- Remove unused Coroutine imports from aspect files
- Improve code maintainability by reducing duplication across aspects

This change ensures coroutine IDs are consistently added to all transactions
and spans through the central Tracer class rather than duplicating the logic
in each individual aspect.
@coderabbitai
Copy link

coderabbitai bot commented Sep 25, 2025

Walkthrough

本次变更在多数 Tracing Aspect 中去除对 Hyperf 协程 ID(coroutine.id)的采集;同时在 Tracer 中为事务与 trace 上下文统一注入 coroutine.id,并为事务设置缺省 startTimestamp、status、source。事件监听器清理了多个事件中对 coroutine.id 与部分 TransactionSource 的设置。Kafka 批量发布增加 message.count 字段。

Changes

Cohort / File(s) Summary
统一移除 Aspect 中的 coroutine.id 采集
src/sentry/src/Tracing/Aspect/AmqpProducerAspect.php, .../AsyncQueueJobMessageAspect.php, .../CacheAspect.php, .../CoordinatorAspect.php, .../CoroutineAspect.php, .../DbAspect.php, .../ElasticsearchAspect.php, .../FilesystemAspect.php, .../GrpcAspect.php, .../GuzzleHttpClientAspect.php, .../RedisAspect.php, .../RpcAspect.php, .../TraceAnnotationAspect.php
移除 Hyperf\Coroutine\Coroutine 引入与 coroutine.id 字段写入;其余流程与数据结构保持不变。
Kafka 发布数据调整
src/sentry/src/Tracing/Aspect/KafkaProducerAspect.php
去除单条与批量发布中的 coroutine.id;批量发布新增 message.count 字段。
事件监听器清理
src/sentry/src/Tracing/Listener/EventHandleListener.php
移除在多类事件(DB、Redis、Crontab、AMQP、Kafka、AsyncQueue 等)中对 coroutine.id 的写入;移除若干场景下显式设置的 TransactionSource
Tracer 统一注入与默认值
src/sentry/src/Tracing/Tracer.php
引入 Hyperf\Engine\CoroutineSentry\Tracing\TransactionSource;在启动事务与 trace 包装时注入 coroutine.id;若缺失则初始化 startTimestampstatus=oksource=custom

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller as 调用方
  participant Tracer as Tracer
  participant Sdk as Sentry SDK

  rect rgba(230,245,255,0.6)
    Note over Tracer: 事务启动时设置默认值与上下文
    Caller->>Tracer: startTransaction(context?)
    Tracer->>Tracer: 若缺失:source=custom, status=ok, startTimestamp=now
    Tracer->>Tracer: context.data += { coroutine.id }
    Tracer->>Sdk: Sdk.startTransaction(context)
    Sdk-->>Tracer: Transaction
    Tracer-->>Caller: Transaction
  end

  rect rgba(240,255,240,0.6)
    Note over Tracer: trace 执行包装统一注入 coroutine.id
    Caller->>Tracer: trace(path, fn, context?)
    Tracer->>Tracer: context.data += { coroutine.id }
    Tracer->>Sdk: Sdk.startSpan(context)
    Sdk-->>Tracer: Span
    Tracer->>Tracer: 执行 fn()
    Tracer->>Sdk: Span.finish()
    Tracer-->>Caller: 返回 fn() 结果
  end

  Note over Caller,Sdk: 各具体 Aspect 不再各自写入 coroutine.id
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • xuanyanwow
  • zds-s

Poem

我在栈间轻轻跳,耳尖数着每步跑;
协程号码藏口袋,统一记录由我保。
Kafka 数量亮闪耀,事务起步不再恼;
咔哒一声提交了,胡萝卜味更香了。 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 该标题精准概括了此次重构的核心变更,即在 Sentry 追踪系统中集中处理 Coroutine ID,从而清理各个 Aspect 中的重复逻辑,完全符合变更内容和目标。
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/centralize-coroutine-id-handling

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.28)

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.

@huangdijia huangdijia merged commit f0429aa into main Sep 25, 2025
15 of 17 checks passed
@huangdijia huangdijia deleted the refactor/centralize-coroutine-id-handling branch September 25, 2025 14:44
huangdijia added a commit that referenced this pull request Sep 25, 2025
…921)

- Remove duplicate coroutine.id data from individual tracing aspects
- Centralize coroutine ID handling in Tracer class for consistency
- Add default transaction metadata (status, source, start timestamp) in Tracer
- Remove unused Coroutine imports from aspect files
- Improve code maintainability by reducing duplication across aspects

This change ensures coroutine IDs are consistently added to all transactions
and spans through the central Tracer class rather than duplicating the logic
in each individual aspect.

Co-authored-by: Deeka Wong <8337659+huangdijia@users.noreply.github.com>
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 (2)
src/sentry/src/Tracing/Aspect/TraceAnnotationAspect.php (1)

47-52: 可选:为 annotation.arguments 增加开关,避免不必要的负载或敏感数据泄露

当前无条件记录所有参数,建议与 annotation.result 一致,受开关控制。

可按下述方式包裹(示例仅展示该段落变更):

-        if (in_array($methodName, ['__call', '__callStatic'])) {
-            $methodName = $proceedingJoinPoint->arguments['keys']['name'] ?? $proceedingJoinPoint->methodName;
-            $data['annotation.arguments'] = $proceedingJoinPoint->arguments['keys']['arguments'] ?? $proceedingJoinPoint->arguments['keys'];
-        } else {
-            $data['annotation.arguments'] = $proceedingJoinPoint->arguments['keys'];
-        }
+        if (in_array($methodName, ['__call', '__callStatic'])) {
+            $methodName = $proceedingJoinPoint->arguments['keys']['name'] ?? $proceedingJoinPoint->methodName;
+            if ($this->switcher->isTracingExtraTagEnabled('annotation.arguments')) {
+                $data['annotation.arguments'] = $proceedingJoinPoint->arguments['keys']['arguments'] ?? $proceedingJoinPoint->arguments['keys'];
+            }
+        } else {
+            if ($this->switcher->isTracingExtraTagEnabled('annotation.arguments')) {
+                $data['annotation.arguments'] = $proceedingJoinPoint->arguments['keys'];
+            }
+        }
src/sentry/src/Tracing/Aspect/KafkaProducerAspect.php (1)

125-126: 批量发布仅设置 message.count,建议补充基础语义字段以对齐单条发布

为便于统一查询/看板,建议与 sendAsync 的数据结构保持一致(system/operation),同时保留 message.count。

可考虑:

-                ->setData(['message.count' => count($messages)])
+                ->setData([
+                    'messaging.system' => 'kafka',
+                    'messaging.operation' => 'publish',
+                    'message.count' => count($messages),
+                ])

如业务保证同批消息同一 topic,可一并添加 messaging.destination.name;否则可省略以避免歧义。

📜 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 67d1e17 and c8e0ef0.

📒 Files selected for processing (16)
  • src/sentry/src/Tracing/Aspect/AmqpProducerAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/AsyncQueueJobMessageAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/CacheAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/CoordinatorAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/CoroutineAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/DbAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/ElasticsearchAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/FilesystemAspect.php (1 hunks)
  • src/sentry/src/Tracing/Aspect/GrpcAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/KafkaProducerAspect.php (1 hunks)
  • src/sentry/src/Tracing/Aspect/RedisAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/RpcAspect.php (0 hunks)
  • src/sentry/src/Tracing/Aspect/TraceAnnotationAspect.php (1 hunks)
  • src/sentry/src/Tracing/Listener/EventHandleListener.php (0 hunks)
  • src/sentry/src/Tracing/Tracer.php (3 hunks)
💤 Files with no reviewable changes (12)
  • src/sentry/src/Tracing/Aspect/AsyncQueueJobMessageAspect.php
  • src/sentry/src/Tracing/Aspect/RedisAspect.php
  • src/sentry/src/Tracing/Aspect/ElasticsearchAspect.php
  • src/sentry/src/Tracing/Aspect/CacheAspect.php
  • src/sentry/src/Tracing/Listener/EventHandleListener.php
  • src/sentry/src/Tracing/Aspect/RpcAspect.php
  • src/sentry/src/Tracing/Aspect/CoordinatorAspect.php
  • src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php
  • src/sentry/src/Tracing/Aspect/DbAspect.php
  • src/sentry/src/Tracing/Aspect/CoroutineAspect.php
  • src/sentry/src/Tracing/Aspect/AmqpProducerAspect.php
  • src/sentry/src/Tracing/Aspect/GrpcAspect.php
🧰 Additional context used
🧬 Code graph analysis (1)
src/sentry/src/Tracing/Tracer.php (1)
src/sentry/class_map/SentrySdk.php (1)
  • SentrySdk (24-65)
⏰ 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). (9)
  • GitHub Check: Test on PHP 8.2 with Swoole 6.0.2
  • GitHub Check: Test on PHP 8.3 with Swoole 5.1.7
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.7
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.7
  • 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 5.1.7
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.7
  • GitHub Check: Test on PHP 8.2 with Swoole 5.1.7
🔇 Additional comments (7)
src/sentry/src/Tracing/Aspect/FilesystemAspect.php (1)

39-39: 去除协程 ID 合并,改用集中注入 —— LGTM

保留原始 $data,遵循统一注入策略,改动合理。

src/sentry/src/Tracing/Tracer.php (5)

15-15: 引入 Hyperf\Engine\Coroutine 与 TransactionSource —— LGTM

满足集中注入与事务来源默认化的需求。

Also applies to: 23-23


44-45: 在 TransactionContext 上集中注入 coroutine.id —— LGTM

使用数组并集避免覆盖既有键,符合预期。


46-53: 为事务设置默认 startTimestamp/status —— LGTM

仅在为空时赋值,避免干扰上游显式设置。


86-87: 在 SpanContext 上集中注入 coroutine.id —— LGTM

与各 Aspect 的精简相匹配,避免重复。


54-56: 确认 sentry-php SDK 版本是否 ≥ v3.9.0,从 v3.9.0 起可直接使用 TransactionContext::setSource();若使用旧版 (<3.9.0),请改为通过 $transactionContext->getMetadata()->setSource(TransactionSource::custom()) 设置来源。

src/sentry/src/Tracing/Aspect/TraceAnnotationAspect.php (1)

44-44: 所有 span 调用均通过 FriendsOfHyperf\Sentry\trace() 注入 coroutine.id,未发现直接调用 Sentry\trace()。

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