Skip to content

Commit c9ae40d

Browse files
huangdijiaCopilot
andcommitted
refactor: centralize context management in Sentry integration (#1035)
* refactor: centralize context management in Sentry integration - Add new Context class to replace Hyperf Context usage - Move all Sentry-specific context constants to Context class - Update all tracing aspects to use centralized context management - Deprecate old Feature class methods in favor of Context class - Standardize server address/port handling across all components - Improve code organization and maintainability This refactor centralizes all context management for Sentry integration, making it easier to maintain and understand the context flow. * refactor: 更新获取Carrier的方法以支持协程ID * refactor: 使用call_user_func获取消息ID以提高兼容性 * refactor: 使用SentryContext替代Hyperf\Context以管理追踪载体 * refactor: 更新SentryContext以支持Elasticsearch和RPC追踪数据管理 * refactor: 优化RPC结果的服务器地址和端口数据设置逻辑 * refactor: 确保服务器地址在缺失时默认为'unknown' * refactor: 替换Context为SentryContext以统一追踪管理 * refactor: 更新SentryContext以使用数据库服务器地址和端口设置 * refactor: 移除不必要的类型转换以简化ElasticsearchSpanData获取逻辑 * refactor: 更新RpcEndpointAspect以使用SentryContext的RPC服务器地址和端口设置 * Apply suggestion from @Copilot Co-authored-by: Copilot <[email protected]> * refactor: 修正TRACE_CARRIER常量的格式以统一命名约定 * refactor: 统一使用Context类替代别名以提高代码可读性 * refactor: 调整TRACE_CARRIER常量的位置以提高代码结构清晰度 * refactor: 统一SentryContext常量命名约定以提高一致性 * refactor: 添加destroyRpcSpanContext方法以简化RPC上下文销毁逻辑 * refactor: 移除不必要的服务器地址和端口常量及相关方法以简化代码 * refactor: 修正CTX_CARRIER常量的命名以提高一致性 * refactor: 修正CTX_RPC_SPAN_CONTEXT常量的命名以提高一致性 * refactor: 移除isTracingEnabled方法以简化代码 * refactor: 强制转换isTracingDisabled方法的返回值为布尔类型 --------- Co-Authored-By: Deeka Wong <[email protected]> Co-Authored-By: Copilot <[email protected]>
1 parent 2768f9b commit c9ae40d

15 files changed

+216
-91
lines changed

src/Constants.php

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,6 @@ class Constants
1515
{
1616
public const TRACE_CARRIER = 'sentry.tracing.trace_carrier';
1717

18-
public const TRACE_DB_SERVER_ADDRESS = 'sentry.tracing.db.server.address';
19-
20-
public const TRACE_DB_SERVER_PORT = 'sentry.tracing.db.server.port';
21-
22-
public const TRACE_REDIS_SERVER_ADDRESS = 'sentry.tracing.redis.server.address';
23-
24-
public const TRACE_REDIS_SERVER_PORT = 'sentry.tracing.redis.server.port';
25-
26-
public const TRACE_RPC_SERVER_ADDRESS = 'sentry.tracing.rpc.server.address';
27-
28-
public const TRACE_RPC_SERVER_PORT = 'sentry.tracing.rpc.server.port';
29-
30-
public const TRACE_ELASTICSEARCH_REQUEST_DATA = 'sentry.tracing.elasticsearch.request.data';
31-
32-
public const CRON_CHECKIN_ID = 'sentry.crons.checkin_id';
33-
34-
public const DISABLE_COROUTINE_TRACING = 'sentry.tracing.coroutine.disabled';
35-
3618
public const SENTRY_TRACE = 'sentry-trace';
3719

3820
public const BAGGAGE = 'baggage';

src/Crons/Listener/EventHandleListener.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@
1111

1212
namespace FriendsOfHyperf\Sentry\Crons\Listener;
1313

14-
use FriendsOfHyperf\Sentry\Constants;
1514
use FriendsOfHyperf\Sentry\Feature;
16-
use Hyperf\Context\Context;
15+
use FriendsOfHyperf\Sentry\SentryContext;
1716
use Hyperf\Contract\ConfigInterface;
1817
use Hyperf\Contract\StdoutLoggerInterface;
1918
use Hyperf\Crontab\Event;
@@ -90,13 +89,13 @@ protected function handleCrontabTaskStarting(Event\BeforeExecute $event, array $
9089
monitorConfig: $monitorConfig,
9190
);
9291

93-
Context::set(Constants::CRON_CHECKIN_ID, $checkInId);
92+
SentryContext::setCronCheckInId($checkInId);
9493
}
9594

9695
protected function handleCrontabTaskFinished(Event\AfterExecute $event): void
9796
{
98-
/** @var null|string $checkInId */
99-
$checkInId = Context::get(Constants::CRON_CHECKIN_ID);
97+
$checkInId = SentryContext::getCronCheckInId();
98+
10099
if (! $checkInId) {
101100
return;
102101
}
@@ -113,8 +112,8 @@ protected function handleCrontabTaskFinished(Event\AfterExecute $event): void
113112

114113
protected function handleCrontabTaskFailed(Event\FailToExecute $event): void
115114
{
116-
/** @var null|string $checkInId */
117-
$checkInId = Context::get(Constants::CRON_CHECKIN_ID);
115+
$checkInId = SentryContext::getCronCheckInId();
116+
118117
if (! $checkInId) {
119118
return;
120119
}

src/Feature.php

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
namespace FriendsOfHyperf\Sentry;
1313

14-
use Hyperf\Context\Context;
1514
use Hyperf\Contract\ConfigInterface;
1615
use Sentry\SentrySdk;
1716

@@ -88,14 +87,4 @@ public function isCronsEnabled(): bool
8887
{
8988
return (bool) $this->config->get('sentry.crons.enable', true);
9089
}
91-
92-
public static function disableCoroutineTracing(): void
93-
{
94-
Context::set(Constants::DISABLE_COROUTINE_TRACING, true);
95-
}
96-
97-
public static function isDisableCoroutineTracing(): bool
98-
{
99-
return (bool) Context::get(Constants::DISABLE_COROUTINE_TRACING);
100-
}
10190
}

src/SentryContext.php

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
/**
5+
* This file is part of friendsofhyperf/components.
6+
*
7+
* @link https://github.com/friendsofhyperf/components
8+
* @document https://github.com/friendsofhyperf/components/blob/main/README.md
9+
* @contact [email protected]
10+
*/
11+
12+
namespace FriendsOfHyperf\Sentry;
13+
14+
use FriendsOfHyperf\Sentry\Util\Carrier;
15+
use Hyperf\Context\Context;
16+
use Sentry\Tracing\SpanContext;
17+
18+
class SentryContext
19+
{
20+
public const CTX_CRON_CHECKIN_ID = 'sentry.ctx.crons.checkin_id';
21+
22+
public const CTX_DISABLE_COROUTINE_TRACING = 'sentry.ctx.coroutine.disabled';
23+
24+
public const CTX_CARRIER = 'sentry.ctx.carrier';
25+
26+
public const CTX_ELASTICSEARCH_SPAN_DATA = 'sentry.ctx.elasticsearch.span.data';
27+
28+
public const CTX_DB_SERVER_ADDRESS = 'sentry.ctx.db.server.address';
29+
30+
public const CTX_DB_SERVER_PORT = 'sentry.ctx.db.server.port';
31+
32+
public const CTX_REDIS_SERVER_ADDRESS = 'sentry.ctx.redis.server.address';
33+
34+
public const CTX_REDIS_SERVER_PORT = 'sentry.ctx.redis.server.port';
35+
36+
public const CTX_RPC_SERVER_ADDRESS = 'sentry.ctx.rpc.server.address';
37+
38+
public const CTX_RPC_SERVER_PORT = 'sentry.ctx.rpc.server.port';
39+
40+
public const CTX_RPC_SPAN_CONTEXT = 'sentry.ctx.rpc.span.context';
41+
42+
public static function disableTracing(): void
43+
{
44+
Context::set(self::CTX_DISABLE_COROUTINE_TRACING, true);
45+
}
46+
47+
public static function enableTracing(): void
48+
{
49+
Context::set(self::CTX_DISABLE_COROUTINE_TRACING, false);
50+
}
51+
52+
public static function isTracingDisabled(): bool
53+
{
54+
return (bool) Context::get(self::CTX_DISABLE_COROUTINE_TRACING, false);
55+
}
56+
57+
public static function setCronCheckInId(string $checkInId): void
58+
{
59+
Context::set(self::CTX_CRON_CHECKIN_ID, $checkInId);
60+
}
61+
62+
public static function getCronCheckInId(): ?string
63+
{
64+
return Context::get(self::CTX_CRON_CHECKIN_ID);
65+
}
66+
67+
public static function setCarrier(Carrier $carrier): void
68+
{
69+
Context::set(self::CTX_CARRIER, $carrier);
70+
}
71+
72+
public static function getCarrier(?int $coroutineId = null): ?Carrier
73+
{
74+
return Context::get(self::CTX_CARRIER, coroutineId: $coroutineId);
75+
}
76+
77+
public static function setRedisServerAddress(string $address): void
78+
{
79+
Context::set(self::CTX_REDIS_SERVER_ADDRESS, $address);
80+
}
81+
82+
public static function getRedisServerAddress(): ?string
83+
{
84+
return Context::get(self::CTX_REDIS_SERVER_ADDRESS);
85+
}
86+
87+
public static function setRedisServerPort(int $port): void
88+
{
89+
Context::set(self::CTX_REDIS_SERVER_PORT, $port);
90+
}
91+
92+
public static function getRedisServerPort(): ?int
93+
{
94+
return Context::get(self::CTX_REDIS_SERVER_PORT);
95+
}
96+
97+
public static function setRpcServerAddress(string $address): void
98+
{
99+
Context::set(self::CTX_RPC_SERVER_ADDRESS, $address);
100+
}
101+
102+
public static function getRpcServerAddress(): ?string
103+
{
104+
return Context::get(self::CTX_RPC_SERVER_ADDRESS);
105+
}
106+
107+
public static function setRpcServerPort(int $port): void
108+
{
109+
Context::set(self::CTX_RPC_SERVER_PORT, $port);
110+
}
111+
112+
public static function getRpcServerPort(): ?int
113+
{
114+
return Context::get(self::CTX_RPC_SERVER_PORT);
115+
}
116+
117+
public static function setDbServerAddress(string $address): void
118+
{
119+
Context::set(self::CTX_DB_SERVER_ADDRESS, $address);
120+
}
121+
122+
public static function getDbServerAddress(): ?string
123+
{
124+
return Context::get(self::CTX_DB_SERVER_ADDRESS);
125+
}
126+
127+
public static function setDbServerPort(int $port): void
128+
{
129+
Context::set(self::CTX_DB_SERVER_PORT, $port);
130+
}
131+
132+
public static function getDbServerPort(): ?int
133+
{
134+
return Context::get(self::CTX_DB_SERVER_PORT);
135+
}
136+
137+
public static function setElasticsearchSpanData(array $data): void
138+
{
139+
Context::set(self::CTX_ELASTICSEARCH_SPAN_DATA, $data);
140+
}
141+
142+
public static function getElasticsearchSpanData(): ?array
143+
{
144+
return Context::get(self::CTX_ELASTICSEARCH_SPAN_DATA);
145+
}
146+
147+
public static function setRpcSpanContext(SpanContext $spanContext): void
148+
{
149+
Context::set(self::CTX_RPC_SPAN_CONTEXT, $spanContext);
150+
}
151+
152+
public static function getRpcSpanContext(): ?SpanContext
153+
{
154+
return Context::get(self::CTX_RPC_SPAN_CONTEXT);
155+
}
156+
157+
public static function destroyRpcSpanContext(): void
158+
{
159+
Context::destroy(self::CTX_RPC_SPAN_CONTEXT);
160+
}
161+
}

src/Tracing/Aspect/AsyncQueueJobMessageAspect.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use FriendsOfHyperf\Sentry\Constants;
1515
use FriendsOfHyperf\Sentry\Feature;
16+
use FriendsOfHyperf\Sentry\SentryContext;
1617
use FriendsOfHyperf\Sentry\Util\Carrier;
1718
use Hyperf\AsyncQueue\Driver\RedisDriver;
1819
use Hyperf\Context\Context;
@@ -77,7 +78,7 @@ public function handlePush(ProceedingJoinPoint $proceedingJoinPoint)
7778

7879
/** @var \Hyperf\AsyncQueue\Driver\Driver $driver */
7980
$driver = $proceedingJoinPoint->getInstance();
80-
$messageId = method_exists($job, 'getId') ? $job->getId() : SentryUid::generate();
81+
$messageId = method_exists($job, 'getId') ? call_user_func([$job, 'getId']) : SentryUid::generate();
8182
$destinationName = Context::get('sentry.messaging.destination.name', 'default');
8283
$bodySize = (fn ($job) => strlen($this->packer->pack($job)))->call($driver, $job);
8384
$data = [
@@ -106,7 +107,7 @@ function (Scope $scope) use ($proceedingJoinPoint, $messageId, $destinationName,
106107
$carrier = Carrier::fromArray([])->with($extra);
107108
}
108109

109-
Context::set(Constants::TRACE_CARRIER, $carrier);
110+
SentryContext::setCarrier($carrier);
110111

111112
return $proceedingJoinPoint->process();
112113
},
@@ -140,7 +141,7 @@ protected function buildSpanDataOfRedisDriver(RedisDriver $driver): array
140141
protected function handleSerialize(ProceedingJoinPoint $proceedingJoinPoint)
141142
{
142143
return with($proceedingJoinPoint->process(), function ($result) {
143-
if (is_array($result) && $carrier = Context::get(Constants::TRACE_CARRIER)) {
144+
if (is_array($result) && $carrier = SentryContext::getCarrier()) {
144145
$result[Constants::TRACE_CARRIER] = $carrier->toJson();
145146
}
146147

@@ -156,7 +157,7 @@ protected function handleUnserialize(ProceedingJoinPoint $proceedingJoinPoint)
156157
$carrier = $data['job'] ?? null;
157158

158159
if ($carrier) {
159-
Context::set(Constants::TRACE_CARRIER, Carrier::fromJson($carrier));
160+
SentryContext::setCarrier(Carrier::fromJson($carrier));
160161
}
161162

162163
return $proceedingJoinPoint->process();

src/Tracing/Aspect/CoroutineAspect.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use FriendsOfHyperf\Sentry\Feature;
1515
use FriendsOfHyperf\Sentry\Integration;
16+
use FriendsOfHyperf\Sentry\SentryContext;
1617
use FriendsOfHyperf\Sentry\Util\CoroutineBacktraceHelper;
1718
use Hyperf\Context\Context;
1819
use Hyperf\Di\Aop\AbstractAspect;
@@ -46,7 +47,7 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
4647
{
4748
if (
4849
! $this->feature->isTracingSpanEnabled('coroutine')
49-
|| Feature::isDisableCoroutineTracing()
50+
|| SentryContext::isTracingDisabled()
5051
) {
5152
return $proceedingJoinPoint->process();
5253
}

src/Tracing/Aspect/DbAspect.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,9 @@
1111

1212
namespace FriendsOfHyperf\Sentry\Tracing\Aspect;
1313

14-
use FriendsOfHyperf\Sentry\Constants;
1514
use FriendsOfHyperf\Sentry\Feature;
15+
use FriendsOfHyperf\Sentry\SentryContext;
1616
use FriendsOfHyperf\Sentry\Util\SqlParser;
17-
use Hyperf\Context\Context;
1817
use Hyperf\DB\Pool\PoolFactory;
1918
use Hyperf\Di\Aop\AbstractAspect;
2019
use Hyperf\Di\Aop\ProceedingJoinPoint;
@@ -71,8 +70,8 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
7170
/** @var \Hyperf\DB\AbstractConnection $connection */
7271
$server = $this->serverCache[$connection] ?? null;
7372
if ($server !== null) {
74-
Context::set(Constants::TRACE_DB_SERVER_ADDRESS, $server['host'] ?? 'localhost');
75-
Context::set(Constants::TRACE_DB_SERVER_PORT, $server['port'] ?? 3306);
73+
SentryContext::setDbServerAddress($server['host'] ?? 'localhost');
74+
SentryContext::setDbServerPort((int) ($server['port'] ?? 3306));
7675
}
7776
});
7877
}
@@ -108,8 +107,8 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
108107
'db.pool.max_idle_time' => $pool->getOption()->getMaxIdleTime(),
109108
'db.pool.idle' => $pool->getConnectionsInChannel(),
110109
'db.pool.using' => $pool->getCurrentConnections(),
111-
'server.host' => Context::get(Constants::TRACE_DB_SERVER_ADDRESS, 'localhost'),
112-
'server.port' => Context::get(Constants::TRACE_DB_SERVER_PORT, 3306),
110+
'server.host' => SentryContext::getDbServerAddress() ?? 'localhost',
111+
'server.port' => SentryContext::getDbServerPort() ?? 3306,
113112
];
114113

115114
if ($this->feature->isTracingTagEnabled('db.sql.bindings', true)) {

src/Tracing/Aspect/DbConnectionAspect.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111

1212
namespace FriendsOfHyperf\Sentry\Tracing\Aspect;
1313

14-
use FriendsOfHyperf\Sentry\Constants;
1514
use FriendsOfHyperf\Sentry\Feature;
15+
use FriendsOfHyperf\Sentry\SentryContext;
1616
use Hyperf\Context\Context;
1717
use Hyperf\Di\Aop\AbstractAspect;
1818
use Hyperf\Di\Aop\ProceedingJoinPoint;
@@ -57,8 +57,8 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
5757
$server = $this->serverCache[$pdo] ?? null;
5858

5959
if (is_array($server)) {
60-
Context::set(Constants::TRACE_DB_SERVER_ADDRESS, $server['host']);
61-
Context::set(Constants::TRACE_DB_SERVER_PORT, $server['port']);
60+
SentryContext::setDbServerAddress($server['host']);
61+
SentryContext::setDbServerPort((int) $server['port']);
6262
}
6363

6464
return true;

src/Tracing/Aspect/ElasticsearchAspect.php

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@
1111

1212
namespace FriendsOfHyperf\Sentry\Tracing\Aspect;
1313

14-
use FriendsOfHyperf\Sentry\Constants;
1514
use FriendsOfHyperf\Sentry\Feature;
16-
use Hyperf\Context\Context;
15+
use FriendsOfHyperf\Sentry\SentryContext;
1716
use Hyperf\Di\Aop\AbstractAspect;
1817
use Hyperf\Di\Aop\ProceedingJoinPoint;
1918
use Sentry\State\Scope;
@@ -59,8 +58,8 @@ function (Scope $scope) use ($proceedingJoinPoint) {
5958
]);
6059
}
6160

62-
$data = (array) Context::get(Constants::TRACE_ELASTICSEARCH_REQUEST_DATA, []);
63-
$scope->getSpan()?->setData($data);
61+
$data = SentryContext::getElasticsearchSpanData();
62+
$data && $scope->getSpan()?->setData($data);
6463
});
6564
},
6665
SpanContext::make()

0 commit comments

Comments
 (0)