Files
sub2api/backend/internal/service/gateway_billing_header.go
T
lishuangqiang 71ef577054 perf(gateway): trim per-request JSON work on the Anthropic request path
- Skip both cache_control walks with a byte-level precheck when the body
  has at most 4 cache_control keys, no thinking block and no 1h TTL; skip
  the block-limit walk when only 1h is present. Bodies containing \u
  escapes always take the original path.
- Replace gjson Array() materialization with Get("0")/ForEach in the
  beta, toolset, tool-rewrite, web-search and system-preview helpers.
- Build the Claude Code mimic debug line lazily; it is only read on
  credential-scope errors.
- Compute the billing-header fingerprint once instead of per block.

Differential tests copy the previous implementations verbatim and
compare byte for byte across edge cases and 3000 randomized bodies.
Batching TTL rewrites with sjson ReplaceInPlace was rejected because it
resolves duplicate keys differently.

Common ~32KB Claude Code request: enforceCacheControlLimit 100us/21
allocs -> 21.6us/0 allocs; helper set 47.6us/103KB -> 37.9us/69KB;
debug line 9.1us/53 allocs -> ~0.
2026-11-11 13:45:09 +08:00

72 lines
2.5 KiB
Go

package service
import (
"fmt"
"regexp"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// ccVersionInBillingRe matches the semver part of cc_version (X.Y.Z).
var ccVersionInBillingRe = regexp.MustCompile(`cc_version=\d+\.\d+\.\d+`)
var ccVersionWithFingerprintInBillingRe = regexp.MustCompile(`cc_version=\d+\.\d+\.\d+\.[0-9a-fA-F]{3}\b`)
// effectiveBillingUserAgent 选择写进 x-anthropic-billing-header 的 User-Agent。
// OAuth mimicry 强制使用调用方传入的 mimicUserAgent(与出站 User-Agent 头同源、
// 同一次请求内取一次复用,保证 cc_version 与出站头版本严格一致),
// 其余情况使用账号指纹 UA。
func effectiveBillingUserAgent(mimicUserAgent, tokenType string, mimicClaudeCode bool, fingerprint *Fingerprint) string {
if tokenType == "oauth" && mimicClaudeCode {
return mimicUserAgent
}
if fingerprint == nil {
return ""
}
return fingerprint.UserAgent
}
// syncBillingHeaderVersion rewrites cc_version in x-anthropic-billing-header
// system text blocks to match the version extracted from userAgent.
// Recompute any recognized fingerprint suffix because its input includes the version.
// Only touches system array blocks whose text starts with "x-anthropic-billing-header".
func syncBillingHeaderVersion(body []byte, userAgent string) []byte {
version := ExtractCLIVersion(userAgent)
if version == "" {
return body
}
systemResult := gjson.GetBytes(body, "system")
if !systemResult.Exists() || !systemResult.IsArray() {
return body
}
replacement := "cc_version=" + version
// The fingerprint depends only on the original messages and version, so it
// is the same for every billing block. Compute it lazily, at most once.
fingerprintedReplacement := ""
idx := 0
systemResult.ForEach(func(_, item gjson.Result) bool {
text := item.Get("text")
if text.Exists() && text.Type == gjson.String &&
strings.HasPrefix(text.String(), "x-anthropic-billing-header") {
if fingerprintedReplacement == "" {
fingerprintedReplacement = replacement + "." + computeClaudeCodeFingerprint(body, version)
}
newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement)
newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement)
if newText != text.String() {
if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil {
body = updated
}
}
}
idx++
return true
})
return body
}