Merge branch 'feat/m46-urlcause-hoist-url-error-unwrapping' into dev
This commit is contained in:
commit
0ec9cbe32b
16 files changed
+517
-138
No files matched your search
@@ -145,7 +145,7 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, target, &buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: build %s %s request: %w", method, host, transportCause(err))
|
||||
return nil, fmt.Errorf("httpclient: build %s %s request: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
@@ -159,13 +159,13 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: %s %s: %w", method, host, transportCause(err))
|
||||
return nil, fmt.Errorf("httpclient: %s %s: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, host, transportCause(err))
|
||||
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, apiFailure(method, host, resp, raw)
|
||||
@@ -209,16 +209,3 @@ func apiFailure(method, host string, resp *http.Response, raw []byte) error {
|
||||
func envelopeMessage(s string) string {
|
||||
return trace.RedactText(strings.Join(strings.Fields(s), " "))
|
||||
}
|
||||
|
||||
// transportCause 剥掉 net/http 的 *url.Error 外壳:它会把**完整请求地址**拼进错误串
|
||||
// (query 里的凭据、user:pass@ 都会跟着走)。剥壳保留内层哨兵链
|
||||
// (context.DeadlineExceeded 等仍可 errors.Is),因此只丢地址、不丢原因。
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径 —— 那份未导出,且服务于入站
|
||||
// 取回路径,本包不能反向依赖它。
|
||||
func transportCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -131,18 +131,26 @@ func TestGetJSON_TransportErrorOmitsTargetCredentials(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestGetJSON_UserinfoNeverEntersError 绝对地址带 user:pass@ 时同样不得出镜。
|
||||
//
|
||||
// 断言用户名而不只是密码:net/http 自己在 *url.Error 里就把密码打成 xxxxx,因此
|
||||
// 「密码不出现」在剥壳与不剥壳两种实现下都成立(这样的用例是空跑);用户名才是
|
||||
// 剥壳与不剥壳的分水岭。
|
||||
func TestGetJSON_UserinfoNeverEntersError(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := New(
|
||||
WithHTTPClient(&http.Client{Transport: failingTransport{}}),
|
||||
WithLogger(discardLogger()),
|
||||
)
|
||||
_, err := c.GetJSON(context.Background(), "https://user:pass@api.example.com/x", nil)
|
||||
_, err := c.GetJSON(context.Background(), "https://leakuser:leakpass@api.example.com/x", nil)
|
||||
if err == nil {
|
||||
t.Fatal("传输层失败却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), "user:pass") {
|
||||
t.Fatalf("user:pass@ 进了错误:%v", err)
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, "leakuser") || strings.Contains(msg, "leakpass") {
|
||||
t.Fatalf("user:pass@ 进了错误:%v", msg)
|
||||
}
|
||||
if !strings.Contains(msg, "api.example.com") {
|
||||
t.Fatalf("剥掉地址时把来源一起丢了:%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/documents"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -179,7 +180,7 @@ func Fetch(ctx context.Context, req Request) ([]byte, error) {
|
||||
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mediafetch: 取回 %s 失败: %w", origin, sanitizeErr(err))
|
||||
return nil, fmt.Errorf("mediafetch: 取回 %s 失败: %w", origin, trace.URLCause(err))
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
@@ -189,7 +190,7 @@ func Fetch(ctx context.Context, req Request) ([]byte, error) {
|
||||
// 边读边限:多读一个字节用来判定「超限」,因此绝不会把一份超大文件读满内存。
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mediafetch: 读取 %s 失败: %w", origin, sanitizeErr(err))
|
||||
return nil, fmt.Errorf("mediafetch: 读取 %s 失败: %w", origin, trace.URLCause(err))
|
||||
}
|
||||
if int64(len(data)) > maxBytes {
|
||||
return nil, fmt.Errorf("%w(上限 %d 字节,来源 %s)", ErrTooLarge, maxBytes, origin)
|
||||
@@ -239,18 +240,6 @@ func applyHeader(dst, src http.Header) {
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeErr 剥掉 *url.Error 的外壳:它会把**完整 URL**(含查询串里的签名凭据)
|
||||
// 拼进错误串。剥壳同时保留内层哨兵链(`context.DeadlineExceeded` 等仍可用
|
||||
// errors.Is 判定)。内层已是最终错误时**原样透传**(这里只做剥壳,不新增包装 ——
|
||||
// 再包一层只会把同一个原因说两遍)。
|
||||
func sanitizeErr(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// originOfURL 把一个已解析的 URL 归一成来源字符串。
|
||||
func originOfURL(u *url.URL) (string, error) {
|
||||
if u == nil {
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
@@ -24,10 +23,6 @@ import (
|
||||
// 错误体是攻击面,不是数据面。
|
||||
const errBodyCap = 512
|
||||
|
||||
// maxErrorTokenBytes 是 error.code / error.type 允许出镜的长度上限(见
|
||||
// safeErrorToken)。
|
||||
const maxErrorTokenBytes = 64
|
||||
|
||||
// upstreamLabel 报「这次调用实际打到哪」:优先主机(自建网关 / 代理下才看得出
|
||||
// 真实去向),取不到主机时退回 provider 名(代码里写死的短名)。两种形态都不含
|
||||
// 路径、查询串与凭据 —— 契约在 trace.HostOf。
|
||||
@@ -45,12 +40,21 @@ func upstreamLabel(name, baseURL string) string {
|
||||
// 而这类 error 会被 `chat run` / `loop step` 打日志。截断到 512 字节只是把
|
||||
// 「整段泄漏」变成「前 512 字节泄漏」,不是修复。
|
||||
//
|
||||
// error.code 也要过令牌守卫(trace.ErrorToken):它在主流上游是枚举,但网关、代理与
|
||||
// 兼容层可以往里面塞任何东西 —— 包括回显的输入。不像令牌的 code 一律变空串,代价只是
|
||||
// 少一条分类提示;status / body 摘要等诊断面不受影响。
|
||||
//
|
||||
// 双 %w:既保持 errors.Is(err, ErrUpstream)(降级链按它分类,主 → 备 → 本地),
|
||||
// 也让 errors.Is(err, trace.ErrUpstream) 成立(调用方按上游失败分类)。
|
||||
func providerUpstreamError(name, baseURL string, resp *http.Response) error {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyCap))
|
||||
info := trace.UpstreamError(upstreamLabel(name, baseURL), resp.StatusCode,
|
||||
resp.Header.Get("Content-Type"), body)
|
||||
info, ok := trace.UpstreamError(upstreamLabel(name, baseURL), resp.StatusCode,
|
||||
resp.Header.Get("Content-Type"), body).(*trace.UpstreamErrorInfo)
|
||||
if !ok {
|
||||
// helper 的构造是固定的,走不到这里;真走到也只少一条诊断,不破安全口径。
|
||||
return fmt.Errorf("model: %w: status %d", ErrUpstream, resp.StatusCode)
|
||||
}
|
||||
info.Code = trace.ErrorToken(info.Code)
|
||||
return fmt.Errorf("model: %w: %w", ErrUpstream, info)
|
||||
}
|
||||
|
||||
@@ -67,26 +71,6 @@ func streamEventError(upstream string, evt *anthropicStreamError) error {
|
||||
// helper 的构造是固定的,走不到这里;真走到也只少一条诊断,不破安全口径。
|
||||
return fmt.Errorf("model: %w: anthropic stream error event", ErrUpstream)
|
||||
}
|
||||
info.Type = safeErrorToken(evt.Type)
|
||||
info.Type = trace.ErrorToken(evt.Type)
|
||||
return fmt.Errorf("model: %w: %w", ErrUpstream, info)
|
||||
}
|
||||
|
||||
// safeErrorToken 只放行「像协议令牌」的短串(字母、数字与 `_ . -`),其余一律
|
||||
// 丢弃。error.code / error.type 在主流上游是枚举,但它们是**自由文本面**:网关、
|
||||
// 代理与兼容层可以往里面塞任何东西。丢弃它的代价只是少一条分类提示,保留一个
|
||||
// 不受控字段的代价是她的话进日志。
|
||||
func safeErrorToken(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" || len(s) > maxErrorTokenBytes {
|
||||
return ""
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
case r == '_' || r == '.' || r == '-':
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package model
|
||||
|
||||
// 本文件钉住 providerUpstreamError 的两条出镜边界:
|
||||
//
|
||||
// - **error.code 是自由文本面**:它在主流上游是枚举,但网关、代理与兼容层可以往
|
||||
// 里面塞任何东西(包括回显的输入)。只有像令牌才出镜,其余变空串 —— 而 status /
|
||||
// type / 体积摘要这些诊断面不受影响。
|
||||
// - **响应体正文一个字节都不进错误**:这是 providerUpstreamError 存在的理由
|
||||
// (旧实现把体截到 512B 拼进 error,而 `chat run` / `loop step` 会把它落日志)。
|
||||
//
|
||||
// 每条用例都是「把它放宽就变红」的形状:断言的是错误的文本,也就是真正进日志的字符串。
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// upstreamErrResp 造一条非 2xx 响应:只带状态码、Content-Type 与体,够
|
||||
// providerUpstreamError 走完整条收敛路径。
|
||||
func upstreamErrResp(status int, body string) *http.Response {
|
||||
return &http.Response{
|
||||
StatusCode: status,
|
||||
Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderUpstreamErrorDropsFreeTextCode code 里是回显的用户原文 ⇒ 该字段整体消失
|
||||
// (连 `code=` 这个键都不出现),而 status / type 仍在。去掉令牌守卫就变红。
|
||||
func TestProviderUpstreamErrorDropsFreeTextCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
const echoed = "Invalid value: '她刚才说的那句话'"
|
||||
body := `{"error":{"code":"` + echoed + `","type":"invalid_request_error"}}`
|
||||
|
||||
err := providerUpstreamError("openai", "https://api.example.com/v1/chat/completions", upstreamErrResp(http.StatusBadRequest, body))
|
||||
if err == nil {
|
||||
t.Fatal("非 2xx 却报成功")
|
||||
}
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, echoed) {
|
||||
t.Fatalf("code 里的用户原文进了错误(会随 chat run 落日志):%v", msg)
|
||||
}
|
||||
if strings.Contains(msg, "code=") {
|
||||
t.Fatalf("非令牌形状的 code 没有被丢弃:%v", msg)
|
||||
}
|
||||
// 诊断面不能一起丢:状态、协议枚举的 type、体积摘要都还在。
|
||||
for _, want := range []string{"status=400", "type=invalid_request_error", "body_bytes=", "api.example.com"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Fatalf("错误里缺少 %q(诊断面不能一起丢):%v", want, msg)
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, ErrUpstream) || !errors.Is(err, trace.ErrUpstream) {
|
||||
t.Fatalf("降级链的哨兵断了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderUpstreamErrorKeepsTokenShapedCode 真实枚举原样出镜:丢掉它只是少一条
|
||||
// 分类提示,但既然它像令牌就该留下。
|
||||
func TestProviderUpstreamErrorKeepsTokenShapedCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
body := `{"error":{"code":"Arrearage","type":"invalid_request_error"}}`
|
||||
|
||||
err := providerUpstreamError("deepseek", "https://api.deepseek.com/v1/chat/completions",
|
||||
upstreamErrResp(http.StatusPaymentRequired, body))
|
||||
if err == nil {
|
||||
t.Fatal("非 2xx 却报成功")
|
||||
}
|
||||
if msg := err.Error(); !strings.Contains(msg, "code=Arrearage") {
|
||||
t.Fatalf("令牌形状的 code 被误杀:%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProviderUpstreamErrorDropsBodyText 体里除了 code/type 之外的字节一个都不进错误:
|
||||
// 上游把用户的提问回显在 error.message 里是真实写法。
|
||||
func TestProviderUpstreamErrorDropsBodyText(t *testing.T) {
|
||||
t.Parallel()
|
||||
const prompt = "她的原始提问:帮我看看这段代码"
|
||||
body := `{"error":{"code":"invalid_request_error","type":"invalid_request_error",` +
|
||||
`"message":"Invalid value: '` + prompt + `'"}}`
|
||||
|
||||
err := providerUpstreamError("openai", "https://api.example.com/v1/chat/completions",
|
||||
upstreamErrResp(http.StatusBadRequest, body))
|
||||
if err == nil {
|
||||
t.Fatal("非 2xx 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), prompt) {
|
||||
t.Fatalf("error.message 的回显进了错误:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -229,13 +229,3 @@ func blockedAddressOf(err error) (*blockedAddressError, bool) {
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// fetchCause 返回取回失败的底层原因:*url.Error 会把整条 URL(含查询串里
|
||||
// 可能的凭据)拼进错误串,这里只取内层错误,哨兵链因此也保留下来。
|
||||
func fetchCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// 读取图像字节与响应体的体积上限,使恶意或
|
||||
@@ -139,7 +141,7 @@ func fetchURL(ctx context.Context, rawURL string, client *http.Client) (string,
|
||||
if blocked, ok := blockedAddressOf(err); ok {
|
||||
return "", nil, blocked
|
||||
}
|
||||
return "", nil, fmt.Errorf("vision: %w: %w", ErrFetch, fetchCause(err))
|
||||
return "", nil, fmt.Errorf("vision: %w: %w", ErrFetch, trace.URLCause(err))
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
|
||||
@@ -18,10 +18,6 @@ import (
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// maxErrorTokenBytes 是 error.code / request_id 允许出镜的长度上限(见
|
||||
// dashscopeErrorToken)。
|
||||
const maxErrorTokenBytes = 64
|
||||
|
||||
// classifyDashscopeStatus 把一个非 200 的 DashScope 响应翻成**可分类**的失败:鉴权失败 /
|
||||
// 欠费额度 / 限流各自成一条哨兵链(都以 ErrProviderFailed 为底),其余原样归入
|
||||
// ErrProviderFailed(切片 IM-ASR 的熔断据此判定「再试是不是白试」)。
|
||||
@@ -45,8 +41,8 @@ func classifyDashscopeStatus(endpoint string, status int, contentType string, bo
|
||||
// helper 的构造是固定的,走不到这里;真走到也只少一条诊断。
|
||||
return fmt.Errorf("voice: %w", sentinel)
|
||||
}
|
||||
info.Code = dashscopeErrorToken(fields.code)
|
||||
if rid := dashscopeErrorToken(fields.requestID); rid != "" {
|
||||
info.Code = trace.ErrorToken(fields.code)
|
||||
if rid := trace.ErrorToken(fields.requestID); rid != "" {
|
||||
return fmt.Errorf("voice: %w: request_id=%s: %w", sentinel, rid, info)
|
||||
}
|
||||
return fmt.Errorf("voice: %w: %w", sentinel, info)
|
||||
@@ -102,35 +98,15 @@ func decodeDashscopeErrorFields(body []byte) dashscopeErrorFields {
|
||||
// message 原文一律不进 error:它是上游自由文本,而这条请求的 input.url 是参考
|
||||
// 音频的公开地址(可能是预签名 URL,带凭据),上游报错经常把它整段回显出来。
|
||||
// 病因分类保留在 ErrProviderFailed(再试也不会好,与既有的熔断口径一致);
|
||||
// 确实带回来的 code/type 也只以令牌形态出镜(过 dashscopeErrorToken)。
|
||||
// 确实带回来的 code/type 也只以令牌形态出镜(过 trace.ErrorToken)。
|
||||
func dashscopeOKBodyError(endpoint string, body []byte) error {
|
||||
info, ok := trace.UpstreamError(trace.HostOf(endpoint), http.StatusOK, "", body).(*trace.UpstreamErrorInfo)
|
||||
if !ok {
|
||||
// helper 的构造是固定的,走不到这里;真走到也只少一条诊断。
|
||||
return fmt.Errorf("voice: %w: dashscope reported a business failure on a 200 response", ErrProviderFailed)
|
||||
}
|
||||
info.Code = dashscopeErrorToken(info.Code)
|
||||
info.Type = dashscopeErrorToken(info.Type)
|
||||
info.Code = trace.ErrorToken(info.Code)
|
||||
info.Type = trace.ErrorToken(info.Type)
|
||||
return fmt.Errorf("voice: %w: dashscope reported a business failure on a 200 response: %w",
|
||||
ErrProviderFailed, info)
|
||||
}
|
||||
|
||||
// dashscopeErrorToken 只放行「像协议令牌」的短串(字母、数字与 `_ . -`):code
|
||||
// 在 DashScope 是枚举(InvalidParameter / Throttling.RateQuota / Arrearage …),
|
||||
// request_id 是十六进制/UUID 形状。两者都是自由文本面,不像令牌的一律丢弃 ——
|
||||
// 宁可少一条分类提示,不让散文借道出镜(同口径见 runtime/model 的 safeErrorToken)。
|
||||
func dashscopeErrorToken(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" || len(s) > maxErrorTokenBytes {
|
||||
return ""
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
case r == '_' || r == '.' || r == '-':
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package voice
|
||||
|
||||
// 本文件钉住 DashScope 错误收口里的**令牌守卫**(trace.ErrorToken):code 与
|
||||
// request_id 都是上游自由文本面 —— code 在 DashScope 是枚举(InvalidParameter /
|
||||
// Throttling.RateQuota / Arrearage …),但网关 / 兼容层可以往里塞任何东西。
|
||||
//
|
||||
// 已有的用例(TestDashscopeTTS_Non200DropsSpokenText)只断言「令牌形状的 code 被
|
||||
// 保留」,去掉守卫它照样通过 —— 那是个半张网。这里补上另一半:**不像令牌的 code
|
||||
// 必须变空串**,而 status / request_id 这些诊断面仍在。
|
||||
//
|
||||
// 形状是「把守去掉就变红」:断言的是错误文本,也就是真正进日志的字符串。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/config"
|
||||
)
|
||||
|
||||
// TestDashscopeTTS_Non200DropsFreeTextCode 4xx 的 code 里放一段散文(带空格与标点)
|
||||
// ⇒ 该字段整体消失(连 `code=` 这个键都不出现),而 status 400 与 request_id 仍在。
|
||||
func TestDashscopeTTS_Non200DropsFreeTextCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
const prose = "Invalid value: '她刚才说的那句话'"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"code":"` + prose + `","request_id":"req-0123456789abcdef"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
tts := NewDashscopeTTS(config.VoiceConfig{DashscopeBaseURL: srv.URL, DashscopeAPIKey: "sk"})
|
||||
_, err := tts.TTS(context.Background(), "随便说点什么")
|
||||
if err == nil {
|
||||
t.Fatal("400 却报成功")
|
||||
}
|
||||
if !errors.Is(err, ErrProviderFailed) {
|
||||
t.Fatalf("err = %v, want ErrProviderFailed(熔断口径不变)", err)
|
||||
}
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, prose) {
|
||||
t.Fatalf("code 里的散文进了错误:%v", msg)
|
||||
}
|
||||
if strings.Contains(msg, "code=") {
|
||||
t.Fatalf("非令牌形状的 code 没有被丢弃:%v", msg)
|
||||
}
|
||||
// 诊断面不能一起丢:状态码与 request_id(对厂商报障时要给的那个)。
|
||||
for _, want := range []string{"status=400", "req-0123456789abcdef"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Fatalf("错误里缺少 %q(诊断面不能一起丢):%v", want, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package trace
|
||||
|
||||
import "strings"
|
||||
|
||||
// 本文件是「上游错误信封里的自由文本字段能不能出镜」的唯一守卫。
|
||||
//
|
||||
// 背景:UpstreamErrorInfo 只解析 error.code / error.type 两个字段,而它们是**自由
|
||||
// 文本面** —— 主流上游里它们确实是枚举(invalid_request_error、overloaded_error、
|
||||
// Throttling.RateQuota …),但网关、代理与兼容层可以往里面塞任何东西,包括回显的
|
||||
// 用户原文。因此这两个字段出镜前必须像令牌:短、只含标识符字符。
|
||||
//
|
||||
// 丢弃的代价只是少一条分类提示;保留一个不受控字段的代价是她的话进日志。这道守卫
|
||||
// 原先在 runtime/model(safeErrorToken)与 runtime/multimodal/voice
|
||||
// (dashscopeErrorToken)各有一份逐字同形的实现,M46 把同一份收敛到这里。
|
||||
|
||||
// maxErrorTokenBytes 是 error.code / error.type / request_id 允许出镜的长度上限。
|
||||
// 64 字节足够容纳任何真实的枚举与 UUID 形状,又远小于「一段话」。
|
||||
const maxErrorTokenBytes = 64
|
||||
|
||||
// ErrorToken 只放行「像协议令牌」的短串(字母、数字与 `_ . -`),其余一律丢弃并返回
|
||||
// 空串 —— 包括带空格、标点、引号的散文,以及超长串。调用方据此决定「这个字段出不
|
||||
// 出镜」,而不是先出镜再清洗。
|
||||
func ErrorToken(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" || len(s) > maxErrorTokenBytes {
|
||||
return ""
|
||||
}
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
case r == '_' || r == '.' || r == '-':
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package trace
|
||||
|
||||
// 本文件钉住 ErrorToken 的唯一职责:error.code / error.type 这类**自由文本面**只有
|
||||
// 「像协议令牌」才允许出镜。它们在上游里是枚举,但网关、代理与兼容层可以往里面塞任何
|
||||
// 东西 —— 包括回显的用户原文。
|
||||
//
|
||||
// 每条用例都是「把它放宽就变红」的形状。
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestErrorTokenKeepsProtocolTokens 真实枚举必须原样通过:丢掉它们的代价是少一条
|
||||
// 分类提示(重试 / 降级 / 熔断的口径)。
|
||||
func TestErrorTokenKeepsProtocolTokens(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, token := range []string{
|
||||
"invalid_request_error",
|
||||
"overloaded_error",
|
||||
"Throttling.RateQuota",
|
||||
"rate-limit",
|
||||
"429",
|
||||
" sparse_error ",
|
||||
} {
|
||||
if got := ErrorToken(token); got != strings.TrimSpace(token) {
|
||||
t.Fatalf("ErrorToken(%q) = %q, want 令牌原值(去首尾空白)", token, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestErrorTokenDropsFreeText 只有像令牌才出镜:带空格、标点、引号的散文一律空串 ——
|
||||
// 那正是「上游把用户原文回显进 code」的形态。
|
||||
func TestErrorTokenDropsFreeText(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, text := range []string{
|
||||
"Invalid value: '她刚才说的那句话'",
|
||||
"prompt is too long",
|
||||
"```json\n{\"a\":1}\n```",
|
||||
"bad,code",
|
||||
"code=1",
|
||||
"",
|
||||
" ",
|
||||
"line\nbreak",
|
||||
"emoji🙂",
|
||||
} {
|
||||
if got := ErrorToken(text); got != "" {
|
||||
t.Fatalf("ErrorToken(%q) = %q, want 空串", text, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestErrorTokenRejectsOverlong 超长串不是令牌(边界 64 字节),否则「话」可以靠长度
|
||||
// 混进来。
|
||||
func TestErrorTokenRejectsOverlong(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := ErrorToken(strings.Repeat("a", 64)); got == "" {
|
||||
t.Fatal("64 字节的令牌被误杀(边界应含)")
|
||||
}
|
||||
if got := ErrorToken(strings.Repeat("a", 65)); got != "" {
|
||||
t.Fatalf("超长串被放行:%q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package trace
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// 本文件是「从 net/http 的 *url.Error 里取回原因」的**唯一**实现。
|
||||
//
|
||||
// 为什么需要它:*url.Error 的 Error() 会把**整条地址**渲染进错误串 ——
|
||||
// `Get "https://h/p?access_token=…": dial tcp …`。而 net/http 在两条路上都会包出它:
|
||||
// 传输层失败(`client.Do`)与地址解析失败(`http.NewRequest`)。这条错误串会进日志、
|
||||
// 进工单、进模型可见视图,而平台的资源地址几乎都带凭据(预签名上传地址的
|
||||
// `encrypted_query_param`、CDN 的 `rkey`、Bot API 路径里的 `/bot<token>/`、OAuth 回调
|
||||
// 里的 `access_token`、user:pass@),于是「原样外抛」等于把凭据写进日志。
|
||||
//
|
||||
// 为什么不能 `fmt.Errorf("...: %w", err)` 直接外抛:%w 只给错误串加前缀,地址仍在串里
|
||||
// —— 包一层不是修复,只是换个位置泄漏。剥壳(取内层 cause)才是。
|
||||
//
|
||||
// 这段逻辑曾被五个客户端各写一份逐字同形的三行(mediafetch.sanitizeErr /
|
||||
// httpclient.transportCause / vision.fetchCause / telegram.callCause /
|
||||
// weixin_ilink.urlFreeCause,共 13 个调用点)。同形实现一分家,最容易发生的漂移是
|
||||
// 「其中一份为了多带点诊断把地址留下来」,而那正是凭据进日志的那一条路 —— 因此收敛
|
||||
// 到这里,调用点只剩一次函数调用(AGENTS.md §10「三次复制必须抽取」)。
|
||||
|
||||
// URLCause 剥掉 err 里**所有层**的 *url.Error 外壳,返回不携带任何 URL 的内层原因。
|
||||
//
|
||||
// 三条口径:
|
||||
// - **逐层剥**:内层若还是 *url.Error(调用方又包了一次 Do、或链上叠了两层),继续
|
||||
// 往下剥 —— 只剥一层的话内层那条仍然带着同一段地址;
|
||||
// - **只丢地址、不丢原因**:返回的是原来的底层 error 本身(不新增包装),因此
|
||||
// errors.Is/As 对 context.Canceled、context.DeadlineExceeded、*net.DNSError 等
|
||||
// 哨兵仍然成立 —— 调用方的分类(重试 / 降级 / 熔断)不受影响,也绝不会把同一个
|
||||
// 原因在文案里说两遍;
|
||||
// - **非 *url.Error 原样返回**:同一个值、不加包装,可安全当作「可能剥壳、也可能
|
||||
// 什么都没做」的透传。
|
||||
//
|
||||
// 唯一的例外是 `*url.Error` 没有内层原因(Err 为 nil)或链自引用:那种错误**无法**
|
||||
// 在不带地址的前提下原样返回,于是退化成只含操作名(Get/Post/parse)的替身 —— 宁可
|
||||
// 少一条原因,也不回落到原串(回落就是泄漏)。net/http 的两处构造都填了 Err,因此
|
||||
// 这条路在真实调用中到不了。
|
||||
func URLCause(err error) error {
|
||||
for {
|
||||
var uerr *url.Error
|
||||
if !errors.As(err, &uerr) {
|
||||
return err
|
||||
}
|
||||
if uerr.Err == nil || uerr.Err == err {
|
||||
return urlOpOnly(uerr.Op)
|
||||
}
|
||||
err = uerr.Err
|
||||
}
|
||||
}
|
||||
|
||||
// urlOpOnly 是「*url.Error 没有可用内层原因」时的替身:只留操作名,地址一个字节都不留。
|
||||
func urlOpOnly(op string) error {
|
||||
return errors.New("url " + op + " failed")
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package trace
|
||||
|
||||
// 本文件钉住 URLCause 的唯一职责:把 *url.Error 剥到内层 cause,且**不携带任何 URL**。
|
||||
//
|
||||
// 为什么值得单独一条:net/http 在传输层失败与地址解析失败时都会包出 *url.Error,
|
||||
// 而它的 Error() 里就是整条地址 —— 平台的资源地址几乎都带签名凭据(预签名 URL、
|
||||
// CDN rkey、Bot API 的 /bot<token>/、OAuth 的 access_token、user:pass@)。旧实现是
|
||||
// 五个客户端各写一份同形的三行剥离,任一份漂移就等于多一条凭据进日志的路。
|
||||
//
|
||||
// 每条用例都是「把它改回去就变红」的形状:断言的是剥壳**之后**的错误文本,也就是
|
||||
// 调用方实际打进日志的那段字符串。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// urlCauseTests 覆盖带凭据的三种地址形态:查询串里的 access_token、user:pass@
|
||||
// 用户信息、以及路径里的 token(Bot API 把 bot token 写在路径里)。
|
||||
var urlCauseTests = []struct {
|
||||
name string
|
||||
rawURL string
|
||||
secret string
|
||||
}{
|
||||
{"query-access-token", "https://cdn.example.com/a/b?access_token=QUERY-ACCESS-TOKEN&x=1", "QUERY-ACCESS-TOKEN"},
|
||||
{"userinfo", "https://user:USER-PASS-SECRET@api.example.com/x", "USER-PASS-SECRET"},
|
||||
{"path-token", "https://api.example.com/bot12345:BOT-TOKEN-SECRET/getUpdates", "BOT-TOKEN-SECRET"},
|
||||
}
|
||||
|
||||
// TestURLCauseStripsURLKeepsCause 剥壳后错误串里只剩原因:地址、路径、查询串、用户
|
||||
// 信息一个片段都不出现,而底层原因仍然在。改回原样 `%w` 外抛(或只剥一层)就变红。
|
||||
func TestURLCauseStripsURLKeepsCause(t *testing.T) {
|
||||
t.Parallel()
|
||||
inner := errors.New("dial tcp 10.0.0.1:443: connection refused")
|
||||
for _, tc := range urlCauseTests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := URLCause(&url.Error{Op: "Get", URL: tc.rawURL, Err: inner})
|
||||
msg := got.Error()
|
||||
if strings.Contains(msg, tc.secret) {
|
||||
t.Fatalf("地址里的凭据进了错误:%v", msg)
|
||||
}
|
||||
for _, fragment := range []string{"https://", "cdn.example.com", "api.example.com", "/bot12345", "?x=1"} {
|
||||
if strings.Contains(msg, fragment) {
|
||||
t.Fatalf("地址片段 %q 进了错误:%v", fragment, msg)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(msg, "connection refused") {
|
||||
t.Fatalf("剥掉地址时把原因一起丢了:%v", msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCauseKeepsSentinelChain 剥壳不得破坏哨兵链:调用方靠 errors.Is 分类
|
||||
// (重试 / 降级 / 熔断),而地址只是副作用面。改回「重新构造一条新错误」就变红。
|
||||
func TestURLCauseKeepsSentinelChain(t *testing.T) {
|
||||
t.Parallel()
|
||||
err := &url.Error{Op: "Get", URL: "https://h/x?access_token=S", Err: context.DeadlineExceeded}
|
||||
got := URLCause(err)
|
||||
if !errors.Is(got, context.DeadlineExceeded) {
|
||||
t.Fatalf("哨兵链断了:%v", got)
|
||||
}
|
||||
if strings.Contains(got.Error(), "access_token") {
|
||||
t.Fatalf("剥壳后仍带地址:%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCauseStripsEveryLayer 内层若还是 *url.Error(调用方又包了一次 Do、或链上
|
||||
// 叠了两层),必须一起剥 —— 只剥一层的话内层那条仍然带着同一段地址。
|
||||
func TestURLCauseStripsEveryLayer(t *testing.T) {
|
||||
t.Parallel()
|
||||
inner := errors.New("connection reset by peer")
|
||||
nested := &url.Error{Op: "Get", URL: "https://inner.example.com/p?access_token=INNER-SECRET", Err: inner}
|
||||
outer := &url.Error{Op: "Get", URL: "https://outer.example.com/p?access_token=OUTER-SECRET", Err: nested}
|
||||
|
||||
msg := URLCause(outer).Error()
|
||||
for _, secret := range []string{"INNER-SECRET", "OUTER-SECRET"} {
|
||||
if strings.Contains(msg, secret) {
|
||||
t.Fatalf("某一层的凭据进了错误(%s):%v", secret, msg)
|
||||
}
|
||||
}
|
||||
if !errors.Is(URLCause(outer), inner) {
|
||||
t.Fatalf("多层剥壳后没回到最内层原因:%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCauseStripsUnderOuterWrapper 调用方用 %w 包过一层时同样剥掉:外层前缀是
|
||||
// 我们自己的文案,带地址的仍然是里层那个 *url.Error。
|
||||
func TestURLCauseStripsUnderOuterWrapper(t *testing.T) {
|
||||
t.Parallel()
|
||||
inner := errors.New("i/o timeout")
|
||||
wrapped := fmt.Errorf("client: %w", &url.Error{Op: "Post", URL: "https://h/p?access_token=WRAPPED-SECRET", Err: inner})
|
||||
msg := URLCause(wrapped).Error()
|
||||
if strings.Contains(msg, "WRAPPED-SECRET") || strings.Contains(msg, "https://") {
|
||||
t.Fatalf("包一层的 *url.Error 仍把地址带了出来:%v", msg)
|
||||
}
|
||||
if !strings.Contains(msg, "i/o timeout") {
|
||||
t.Fatalf("剥掉地址时把原因一起丢了:%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCausePassesThroughNonURL 非 *url.Error 原样返回(同一个值、不加包装):
|
||||
// 五个调用点把它当「可能剥壳、可能什么都没做」的透传,多包一层会把同一个原因在
|
||||
// 文案里说两遍。
|
||||
func TestURLCausePassesThroughNonURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
sentinel := errors.New("boom")
|
||||
if got := URLCause(sentinel); got != sentinel {
|
||||
t.Fatalf("非 *url.Error 被改写了:got %v", got)
|
||||
}
|
||||
wrapped := fmt.Errorf("ctx: %w", sentinel)
|
||||
if got := URLCause(wrapped); got != wrapped {
|
||||
t.Fatalf("非 *url.Error 的包装被拆开了:got %v", got)
|
||||
}
|
||||
if got := URLCause(nil); got != nil {
|
||||
t.Fatalf("nil 被改写成了 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCauseWithoutCauseStaysURLLess *url.Error 没有内层原因时(Err 为 nil)也无法
|
||||
// 原样返回 —— 它照样会把地址渲染进 Error()。此时只留操作名:宁可少一条原因,也不
|
||||
// 回落到原串。改回「Err 为 nil 就 return err」就变红。
|
||||
func TestURLCauseWithoutCauseStaysURLLess(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := URLCause(&url.Error{Op: "Get", URL: "https://h/p?access_token=NIL-CAUSE-SECRET"})
|
||||
if got == nil {
|
||||
t.Fatal("返回了 nil")
|
||||
}
|
||||
msg := got.Error()
|
||||
if strings.Contains(msg, "NIL-CAUSE-SECRET") || strings.Contains(msg, "https://") {
|
||||
t.Fatalf("没有内层原因时回落到了原串(泄漏地址):%v", msg)
|
||||
}
|
||||
if !strings.Contains(msg, "Get") {
|
||||
t.Fatalf("连操作名都没留下(诊断面全丢):%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestURLCauseSelfReferentialChainTerminates 自引用的错误链不能让剥壳死循环。
|
||||
func TestURLCauseSelfReferentialChainTerminates(t *testing.T) {
|
||||
t.Parallel()
|
||||
self := &url.Error{Op: "Post", URL: "https://h/p?access_token=SELF-SECRET"}
|
||||
self.Err = self
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- URLCause(self) }()
|
||||
select {
|
||||
case got := <-done:
|
||||
if got == nil {
|
||||
t.Fatal("返回了 nil")
|
||||
}
|
||||
if strings.Contains(got.Error(), "SELF-SECRET") {
|
||||
t.Fatalf("自引用链把地址带了出来:%v", got)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("URLCause 在自引用链上没有终止")
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,9 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -40,9 +38,9 @@ func (a *Adapter) doJSON(ctx context.Context, method string, payload any) (*botR
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint(method), &buf)
|
||||
if err != nil {
|
||||
// 解析失败的 err 同样是 *url.Error(里面是整条 /bot<token>/… 地址),因此与
|
||||
// 下面的传输层分支同形处理:只留来源,地址由 callCause 剥掉。
|
||||
// 下面的传输层分支同形处理:只留来源,地址由 trace.URLCause 剥掉。
|
||||
return nil, fmt.Errorf("telegram: build %s request %s: %w",
|
||||
method, trace.HostOf(a.endpoint(method)), callCause(err))
|
||||
method, trace.HostOf(a.endpoint(method)), trace.URLCause(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
@@ -51,7 +49,7 @@ func (a *Adapter) doJSON(ctx context.Context, method string, payload any) (*botR
|
||||
if err != nil {
|
||||
// 只留来源:Bot API 把 token 写在地址路径里(/bot<token>/<method>),而
|
||||
// *url.Error 会把整条地址拼进错误串 —— 原样 `%w` 等于把 bot token 写进日志。
|
||||
return nil, fmt.Errorf("telegram: %s call %s: %w", method, trace.HostOf(a.endpoint(method)), callCause(err))
|
||||
return nil, fmt.Errorf("telegram: %s call %s: %w", method, trace.HostOf(a.endpoint(method)), trace.URLCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -236,14 +234,3 @@ func badResponseError(method string, status int, body []byte) error {
|
||||
func boundedDescription(s string) string {
|
||||
return trace.RedactText(strings.Join(strings.Fields(s), " "))
|
||||
}
|
||||
|
||||
// callCause 剥掉 net/http 的 *url.Error 外壳:它会把完整地址拼进错误串,而 Bot API
|
||||
// 的地址路径里就写着 bot token。剥壳只丢地址,内层哨兵链(context 取消等)原样保留。
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径(那份未导出,且在别包里)。
|
||||
func callCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -78,12 +77,12 @@ func (a *Adapter) doJSON(ctx context.Context, method, rawURL string, body io.Rea
|
||||
host := mediafetch.HostOf(rawURL)
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("weixin_ilink: build %s %s: %w", method, host, urlFreeCause(err))
|
||||
return fmt.Errorf("weixin_ilink: build %s %s: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
a.authorizationHeader(req)
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("weixin_ilink: %s %s: %w", method, host, urlFreeCause(err))
|
||||
return fmt.Errorf("weixin_ilink: %s %s: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
@@ -93,7 +92,7 @@ func (a *Adapter) doJSON(ctx context.Context, method, rawURL string, body io.Rea
|
||||
}
|
||||
if out == nil {
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return fmt.Errorf("weixin_ilink: drain %s %s: %w", method, host, urlFreeCause(err))
|
||||
return fmt.Errorf("weixin_ilink: drain %s %s: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -103,21 +102,6 @@ func (a *Adapter) doJSON(ctx context.Context, method, rawURL string, body io.Rea
|
||||
return nil
|
||||
}
|
||||
|
||||
// urlFreeCause 剥掉 net/http 的 *url.Error 外壳:它会把**整条地址**拼进错误串 ——
|
||||
// doJSON 的地址、uploadCiphertext 的预签名上传地址(`encrypted_query_param` 就是下载
|
||||
// 凭据)都会跟着进错误与日志。剥壳只丢地址,内层哨兵链(context 取消、*net.DNSError
|
||||
// 等)原样保留,因此 fetchErrCategory 的归类不受影响。
|
||||
//
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径:那份是未导出符号,且只服务
|
||||
// 于入站取回路径(mediafetch 不感知本包的发送侧),因此这里保留一份同形的三行实现。
|
||||
func urlFreeCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// apiURL 把路径与已配置的基础 URL 拼接起来。
|
||||
func (a *Adapter) apiURL(path string) string {
|
||||
return joinURL(a.cfg.BaseURL, path)
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/mediafetch"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -232,12 +233,12 @@ func (a *Adapter) uploadOnce(ctx context.Context, uploadURL string, data []byte)
|
||||
host := mediafetch.HostOf(uploadURL)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, uploadURL, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("weixin_ilink: build upload to %s: %w", host, urlFreeCause(err))
|
||||
return "", false, fmt.Errorf("weixin_ilink: build upload to %s: %w", host, trace.URLCause(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", true, fmt.Errorf("weixin_ilink: upload media to %s: %w", host, urlFreeCause(err))
|
||||
return "", true, fmt.Errorf("weixin_ilink: upload media to %s: %w", host, trace.URLCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
Reference in new issue
Block a user