Files
sub2api/backend/internal/service/json_escape_probe.go
T
feeeei ade20f4e47 perf(gateway): 请求体热点路径改用零拷贝读取,减少整段解码与复制
大请求体上,几个只读检查一遇到任意 \u 转义就整段解码,gjson.GetBytes 会复制整段
input/messages,sjson 删除不存在的键时也会先复制整个 body。

- 新增 JSONMayEscapePlainASCII:成对扫描 JSON 转义,只有能拼出可见 ASCII 的 \u 才让
  字面量快速判断失效;控制字符、HTML 安全转义和非 ASCII 字符的转义不再触发完整解码。
  用于 codex bootstrap / page context 候选、compaction_trigger、input_image、
  additional_tools 的快速判断。
- OpenAI Responses:
  - namespace 声明、tools 判断、空 base64 图片、compaction_trigger 检测与 namespace
    剥离改用 parseRawJSONView,不再复制整段 input/tools。
  - compaction_trigger 只字面出现一次且是 input 最后一项的 type 时跳过完整解码。
  - codex 调用输出候选在字面量命中后,用零拷贝视图确认 input 中确有对应名字的
    function_call_output 项;只在工具声明里出现同名时不再做唯一性扫描和完整解码。
- Bedrock:
  - 顶层字段删除前先用零拷贝视图确认存在。
  - cache_control 清理和流事件 bytes 字段改用零拷贝读取。
- NormalizeMaxReasoningEffort 复用包级 strings.Replacer。

合法 JSON 上行为不变,新增测试与总走解码/复制的参考实现做差分比较。只在非法或病态
body 上有差异:嵌套超过 10000 层且只含非 ASCII 转义、或 trigger 已在末尾时,不再报
解码深度错误(gjson 校验没有深度上限,无字面量 body 原本即如此);开头带非 JSON
前缀的非法 body,零拷贝视图读不到其后的对象,这类 body 随后仍被 JSON 校验拒绝。
2026-11-15 00:05:38 +08:00

72 lines
1.9 KiB
Go

package service
import "bytes"
// JSONMayEscapePlainASCII reports whether body contains a \u escape that spells a
// printable ASCII character no JSON encoder needs to escape (letters, digits,
// underscore, most punctuation). Only such an escape can hide a keyword made of
// those characters from a literal byte search, so when this returns false a
// bytes.Contains miss for such a keyword is a reliable negative. Keywords that
// contain an ignored character below need their own check.
//
// Escapes that encoders do emit on real traffic are ignored: control
// characters (the ANSI escape in shell output), quote, backslash, apostrophe,
// Go's HTML-safe escapes of <, > and &, and every non-ASCII rune. Large agent
// requests therefore keep their fast paths instead of being fully decoded. A
// malformed or truncated escape is reported as true to stay conservative.
//
// Escapes are consumed pairwise, so an escaped backslash followed by a literal
// u (Windows paths, regexes, code samples) is plain text, not an escape.
func JSONMayEscapePlainASCII(body []byte) bool {
for i := 0; ; {
j := bytes.IndexByte(body[i:], '\\')
if j < 0 {
return false
}
next := i + j + 1
if next >= len(body) {
return true
}
if body[next] != 'u' {
i = next + 1
continue
}
if next+5 > len(body) {
return true
}
r, ok := parseJSONHex4(body[next+1 : next+5])
if !ok || jsonEscapeHidesPlainASCII(r) {
return true
}
i = next + 5
}
}
func parseJSONHex4(b []byte) (rune, bool) {
var r rune
for _, c := range b {
switch {
case c >= '0' && c <= '9':
r = r<<4 | rune(c-'0')
case c >= 'a' && c <= 'f':
r = r<<4 | rune(c-'a'+10)
case c >= 'A' && c <= 'F':
r = r<<4 | rune(c-'A'+10)
default:
return 0, false
}
}
return r, true
}
func jsonEscapeHidesPlainASCII(r rune) bool {
if r < 0x20 || r >= 0x7f {
return false
}
switch r {
case '"', '\\', '<', '>', '&', '\'':
return false
}
return true
}