Skip to content

Conversation

@huangdijia
Copy link
Contributor

@huangdijia huangdijia commented Sep 4, 2025

Summary

  • Standardize HTTP response field names in GuzzleHttpClientAspect to follow HTTP semantic conventions
  • Update configuration key to match new field naming
  • Improve HTTP status-based span status handling

Changes

  • response.statushttp.response.status_code
  • response.reasonhttp.response.reason
  • response.headershttp.response.headers
  • response.body.sizehttp.response.body.size
  • response.bodyhttp.response.body.contents
  • Update config key from response.body to http.response.body.contents
  • Add proper HTTP status-based span status setting using SpanStatus::createFromHttpStatusCode()
  • Improve error handling with standardized field names

Test plan

  • Verify HTTP tracing still works correctly with new field names
  • Test configuration option http.response.body.contents works as expected
  • Confirm span status is properly set based on HTTP status codes
  • Validate error scenarios still capture appropriate data

Summary by CodeRabbit

  • 新功能

    • 自动依据 HTTP 状态码设置追踪 Span 状态,4xx/5xx 仍标记为错误
    • 可选上报异常堆栈信息,提升问题定位能力
  • 重构

    • 统一追踪标签为 http.response.*(含 status_code、reason、headers、body.size)
    • 响应体内容标签键更名为 http.response.body.contents,配置开关保持不变

…ntAspect

- Update response field names to follow HTTP semantic conventions
- Change response.status to http.response.status_code
- Change response.reason to http.response.reason
- Change response.headers to http.response.headers
- Change response.body.size to http.response.body.size
- Change response.body to http.response.body.contents
- Update configuration key from response.body to http.response.body.contents
- Add proper HTTP status-based span status setting
- Improve error handling with standardized field names
@coderabbitai
Copy link

coderabbitai bot commented Sep 4, 2025

Walkthrough

该变更统一了 HTTP 响应相关的追踪标签命名(由 response.* 迁移到 http.response.*),在 Guzzle 拦截器中补充了基于状态码的 span 状态设置,并微调异常与响应体记录逻辑;同时在发布配置中同步更新了对应的 extra_tags 键名。

Changes

Cohort / File(s) Summary of changes
配置标签重命名
src/sentry/publish/sentry.php
在 tracing.extra_tags 中将键名从 `response.body` 重命名为 `http.response.body.contents`,布尔值保持为 false。
Guzzle 拦截与标签/状态处理
src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php
将响应相关标签由 `response.` 统一重命名为 `http.response.`;新增基于 HTTP 状态码的 `span->setStatus(SpanStatus::createFromHttpStatusCode(...))`;响应体内容标签改为 `http.response.body.contents` 并受对应开关控制;异常信息合并写入(message、stack_trace 受开关控制);保留 error 标记与原因标签键名调整。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant A as Caller
  participant H as GuzzleHttpClientAspect
  participant G as Guzzle Client
  participant S as Sentry Span

  A->>H: 发起 HTTP 请求
  H->>S: 创建/获取 Span
  H->>G: 发送请求(可能覆写请求头)
  G-->>H: 返回 Response 或抛出异常

  alt 成功
    H->>S: setStatus(createFromHttpStatusCode)
    H->>S: setTags(http.response.status_code, reason, headers, body.size)
    opt 开启 http.response.body.contents
      H->>S: setTag(http.response.body.contents)
    end
    H-->>A: 返回 Response
  else 异常
    H->>S: setTag(error=true)
    H->>S: setTags(exception.class, exception.code, exception.message)
    opt 开启 exception.stack_trace
      H->>S: setTag(exception.stack_trace)
    end
    H-->>A: 抛出异常
  end

  note over H,S: 所有原 response.* 标签迁移为 http.response.*
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • guandeng
  • xuanyanwow

Poem

代码田里风微拂,键帽如麦随风伏。
我把标签重新梳,http 路径更清楚。
状态一判心不俗,异常栈影轻轻录。
小兔拍爪蹦两步:追踪之旅再起步。 🐇✨

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

Note: Using configuration file /phpstan.neon.dist.
At least one path must be specified to analyse.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/tracing-standardize-http-response-fields

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@huangdijia huangdijia merged commit 5b5ad83 into main Sep 4, 2025
16 of 17 checks passed
@huangdijia huangdijia deleted the fix/tracing-standardize-http-response-fields branch September 4, 2025 11:14
huangdijia added a commit that referenced this pull request Sep 4, 2025
…ntAspect (#899)

- Update response field names to follow HTTP semantic conventions
- Change response.status to http.response.status_code
- Change response.reason to http.response.reason
- Change response.headers to http.response.headers
- Change response.body.size to http.response.body.size
- Change response.body to http.response.body.contents
- Update configuration key from response.body to http.response.body.contents
- Add proper HTTP status-based span status setting
- Improve error handling with standardized field names

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

🧹 Nitpick comments (4)
src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php (4)

84-85: 注释说明到位;可考虑避免覆盖已有传播头

当前用 array_replace 强制覆盖 sentry-trace/traceparent/baggage。如果调用方已注入这些头,覆盖可能引入链路断裂。可改为仅在目标头缺失时写入,或做不区分大小写的合并策略。


118-124: 字段重命名对齐语义规范,建议对 headers 做脱敏/裁剪

改为 http.response.* 👍。为降低体积与敏感信息风险,建议对 http.response.headers 进行:

  • 脱敏:过滤/哈希 Authorization、Cookie、Set-Cookie 等。
  • 裁剪:限制头数量或总字节数,超限用占位符标记。

134-137: 避免在 tags 中记录高基数的 reason

已在 data 中写入 http.response.reason;建议在 tags 仅保留 error=true(或同时保留 status_code),移除 reason,避免可能的高基数字段污染指标/聚合。

-                    $span->setTags([
-                        'error' => true,
-                        'http.response.reason' => $response->getReasonPhrase(),
-                    ]);
+                    $span->setTags([
+                        'error' => true,
+                        // 可选:如需保留,改为低基数字段
+                        // 'http.response.status_code' => (string) $response->getStatusCode(),
+                    ]);

150-153: 将 exception.message 的开关与 stack_trace 解耦

目前异常 message 与 stack_trace 共用一个开关。建议为 message 增加独立配置键(如 exception.message),或默认记录受限长度的 message,以便在不开启堆栈时也能定位问题。

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5fb891c and 880b924.

📒 Files selected for processing (2)
  • src/sentry/publish/sentry.php (1 hunks)
  • src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php (1)
src/sentry/src/Switcher.php (1)
  • isTracingExtraTagEnable (53-56)
⏰ 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). (10)
  • 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.2 with Swoole 5.1.7
  • 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.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 6.0.2
  • GitHub Check: Test on PHP 8.1 with Swoole 5.1.7
🔇 Additional comments (2)
src/sentry/publish/sentry.php (1)

118-118: 补充全局替换脚本并更新发布说明

  • 请使用支持 lookaround 的命令(如 rg --pcre2 -n 'response\.body(?!\.size)' -S)或等效正则(例如 rg -n 'response\.body' -S \| grep -Ev 'response\.body\.size')重新检查 response.bodyresponse.body.size 外的残留引用
  • 新键名 http.response.body.contents 已在 src/sentry/publish/sentry.php(118 行)和 src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php(126–127 行)中使用,确认文档及变更日志/升级指南中已说明此破坏性变更并同步示例代码
src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php (1)

131-131: 基于状态码设置 SpanStatus ✅

使用 SpanStatus::createFromHttpStatusCode() 正确、可读性好,与 Sentry 语义一致。

Comment on lines +126 to 129
if ($this->switcher->isTracingExtraTagEnable('http.response.body.contents')) {
$data['http.response.body.contents'] = $response->getBody()->getContents();
$response->getBody()->isSeekable() && $response->getBody()->rewind();
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

读取响应体应限流并按类型白名单,避免内存放大与隐私泄露

当前直接 getContents() 会读完整正文(可能为大文件/二进制)。建议:

  • 仅对白名单类型(text/*、application/json 等)采集;
  • 设定最大读取字节(如 8KB),其余以占位符替代;
  • 仍保留 rewind 逻辑。

可在本段直接替换为(使用完全限定名避免新增 use):

-                if ($this->switcher->isTracingExtraTagEnable('http.response.body.contents')) {
-                    $data['http.response.body.contents'] = $response->getBody()->getContents();
-                    $response->getBody()->isSeekable() && $response->getBody()->rewind();
-                }
+                if ($this->switcher->isTracingExtraTagEnable('http.response.body.contents')) {
+                    $body = $response->getBody();
+                    $contentType = $response->getHeaderLine('Content-Type');
+                    $isTextual = \preg_match('/^(text\/|application\/(json|xml|x-www-form-urlencoded))/i', $contentType) === 1;
+                    $data['http.response.body.contents'] = $isTextual
+                        ? \GuzzleHttp\Psr7\Utils::copyToString($body, 8192)  // 8KB 上限
+                        : '[binary omitted]';
+                    $body->isSeekable() && $body->rewind();
+                }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ($this->switcher->isTracingExtraTagEnable('http.response.body.contents')) {
$data['http.response.body.contents'] = $response->getBody()->getContents();
$response->getBody()->isSeekable() && $response->getBody()->rewind();
}
if ($this->switcher->isTracingExtraTagEnable('http.response.body.contents')) {
$body = $response->getBody();
$contentType = $response->getHeaderLine('Content-Type');
$isTextual = \preg_match('/^(text\/|application\/(json|xml|x-www-form-urlencoded))/i', $contentType) === 1;
$data['http.response.body.contents'] = $isTextual
? \GuzzleHttp\Psr7\Utils::copyToString($body, 8192) // 8KB 上限
: '[binary omitted]';
$body->isSeekable() && $body->rewind();
}
🤖 Prompt for AI Agents
In src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php around lines
126-129, replace the unconditional getContents() with logic that first inspects
the response Content-Type header and only proceeds for a whitelist of safe
text-like types (e.g., text/*, application/json, application/xml,
application/*+json, application/*+xml); for whitelist matches read at most 8192
bytes from the body (use stream read/getContents with a byte limit or
stream->read(8192)), and if the body is larger append a placeholder like
"[TRUNCATED]" (optionally including original size); for non-whitelisted or
binary types do not collect body contents; always preserve the existing rewind
call when the stream is seekable; implement this replacement inline and avoid
adding new use statements (use fully qualified names if needed).

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