mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 16:04:24 +00:00
Merge pull request #8868 from lishuangqiang/perf/gateway-request-single-scan
perf(gateway): parse the request body once instead of eight times
This commit is contained in:
5 files changed
+558
-36
No files matched your search
@@ -174,8 +174,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
|
||||
defer inflightRelease()
|
||||
|
||||
// Parse request for session hash
|
||||
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
|
||||
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
|
||||
bodyRef := service.NewRequestBodyRef(body)
|
||||
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions")
|
||||
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions")
|
||||
if parsedReq == nil {
|
||||
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
|
||||
}
|
||||
|
||||
@@ -181,8 +181,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
|
||||
defer inflightRelease()
|
||||
|
||||
// Parse request for session hash
|
||||
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
|
||||
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
|
||||
bodyRef := service.NewRequestBodyRef(body)
|
||||
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses")
|
||||
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses")
|
||||
if parsedReq == nil {
|
||||
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
|
||||
}
|
||||
|
||||
@@ -189,29 +189,115 @@ func clearGatewayRequestRanges(parsed *ParsedRequest) {
|
||||
parsed.inputRange = missingJSONRange()
|
||||
}
|
||||
|
||||
func setGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) {
|
||||
// gatewayRequestRootFields 保存一次根对象遍历取到的原始值视图。全部零拷贝,
|
||||
// 只在本次解析内使用,body 被改写后必须重新扫描。
|
||||
//
|
||||
// 嵌套字段按 gjson.Get 的语义取值:路径的每一段都取「第一个能解析出子键的同名键」,
|
||||
// 而不是简单取第一个同名键。例如 {"metadata":"x","metadata":{"user_id":"u"}} 在
|
||||
// gjson.Get("metadata.user_id") 下取到 "u",这里以 Exists() 作为「还没取到」的判据
|
||||
// 复现该重试行为。
|
||||
type gatewayRequestRootFields struct {
|
||||
model gjson.Result
|
||||
stream gjson.Result
|
||||
maxTokens gjson.Result
|
||||
metadataUID gjson.Result
|
||||
thinkingType gjson.Result
|
||||
outputEffort gjson.Result
|
||||
speed gjson.Result
|
||||
system gjson.Result
|
||||
messages gjson.Result
|
||||
input gjson.Result
|
||||
contents gjson.Result
|
||||
geminiSysParts gjson.Result
|
||||
}
|
||||
|
||||
// scanGatewayRequestRoot 用一次根对象遍历取出解析需要的全部字段。
|
||||
//
|
||||
// 逐字段 gjson.Get 的问题在于「键不存在」也要把整份 body 扫一遍才能返回不存在:
|
||||
// 1 MiB body 上每个缺失键约 142µs,而一次完整遍历约 220µs——解析一次要做 7 次查找,
|
||||
// 其中 6 个键(metadata.user_id / thinking.type / output_config.effort / max_tokens /
|
||||
// system / messages)在典型 Responses 请求里都不存在。
|
||||
func scanGatewayRequestRoot(body []byte) gatewayRequestRootFields {
|
||||
var f gatewayRequestRootFields
|
||||
parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool {
|
||||
switch key.Str {
|
||||
case "model":
|
||||
if !f.model.Exists() {
|
||||
f.model = value
|
||||
}
|
||||
case "stream":
|
||||
if !f.stream.Exists() {
|
||||
f.stream = value
|
||||
}
|
||||
case "max_tokens":
|
||||
if !f.maxTokens.Exists() {
|
||||
f.maxTokens = value
|
||||
}
|
||||
case "metadata":
|
||||
if !f.metadataUID.Exists() {
|
||||
f.metadataUID = value.Get("user_id")
|
||||
}
|
||||
case "thinking":
|
||||
if !f.thinkingType.Exists() {
|
||||
f.thinkingType = value.Get("type")
|
||||
}
|
||||
case "output_config":
|
||||
if !f.outputEffort.Exists() {
|
||||
f.outputEffort = value.Get("effort")
|
||||
}
|
||||
case "speed":
|
||||
if !f.speed.Exists() {
|
||||
f.speed = value
|
||||
}
|
||||
case "system":
|
||||
if !f.system.Exists() {
|
||||
f.system = value
|
||||
}
|
||||
case "messages":
|
||||
if !f.messages.Exists() {
|
||||
f.messages = value
|
||||
}
|
||||
case "input":
|
||||
if !f.input.Exists() {
|
||||
f.input = value
|
||||
}
|
||||
case "contents":
|
||||
if !f.contents.Exists() {
|
||||
f.contents = value
|
||||
}
|
||||
case "systemInstruction":
|
||||
if !f.geminiSysParts.Exists() {
|
||||
f.geminiSysParts = value.Get("parts")
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func setGatewayRequestRangesFromFields(parsed *ParsedRequest, protocol string, fields gatewayRequestRootFields) {
|
||||
if parsed == nil {
|
||||
return
|
||||
}
|
||||
switch protocol {
|
||||
case domain.PlatformGemini:
|
||||
if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() {
|
||||
parsed.systemRange = rangeFromResult(sysParts)
|
||||
if fields.geminiSysParts.Exists() && fields.geminiSysParts.IsArray() {
|
||||
parsed.systemRange = rangeFromResult(fields.geminiSysParts)
|
||||
}
|
||||
if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(contents)
|
||||
if fields.contents.Exists() && fields.contents.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(fields.contents)
|
||||
}
|
||||
default:
|
||||
if sys := gjson.Get(jsonStr, "system"); sys.Exists() {
|
||||
if fields.system.Exists() {
|
||||
parsed.HasSystem = true
|
||||
parsed.systemRange = rangeFromResult(sys)
|
||||
parsed.systemRange = rangeFromResult(fields.system)
|
||||
}
|
||||
if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(msgs)
|
||||
if fields.messages.Exists() && fields.messages.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(fields.messages)
|
||||
}
|
||||
if protocol == "responses" {
|
||||
if input := gjson.Get(jsonStr, "input"); input.Exists() {
|
||||
parsed.inputRange = rangeFromResult(input)
|
||||
if fields.input.Exists() {
|
||||
parsed.inputRange = rangeFromResult(fields.input)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,31 +315,32 @@ func normalizeClaudeCodeLongContextModel(model string) string {
|
||||
return model
|
||||
}
|
||||
|
||||
// parseGatewayRequestCurrentBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。
|
||||
func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error {
|
||||
// parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。
|
||||
// validate 为 false 时要求调用方已经确认 body 是合法 JSON(见 ParseGatewayRequestValidated)。
|
||||
func parseGatewayRequestBody(parsed *ParsedRequest, protocol string, validate bool) error {
|
||||
if parsed == nil || parsed.Body == nil {
|
||||
return fmt.Errorf("empty request body")
|
||||
}
|
||||
parsed.Body.parsed = nil
|
||||
|
||||
bodyBytes := parsed.Body.Bytes()
|
||||
if !gjson.ValidBytes(bodyBytes) {
|
||||
if validate && !gjson.ValidBytes(bodyBytes) {
|
||||
return DescribeInvalidJSON(bodyBytes)
|
||||
}
|
||||
|
||||
// Zero-copy JSON reads stay local to parsing. Persisted scalar strings must
|
||||
// own their storage: an unescaped gjson string otherwise retains the complete
|
||||
// request buffer when copied into queued billing work. Raw ranges stay zero-copy.
|
||||
jsonStr := *(*string)(unsafe.Pointer(&bodyBytes))
|
||||
clearGatewayRequestDerivedState(parsed)
|
||||
parsed.protocol = protocol
|
||||
|
||||
modelResult := gjson.Get(jsonStr, "model")
|
||||
if modelResult.Exists() {
|
||||
if modelResult.Type != gjson.String {
|
||||
fields := scanGatewayRequestRoot(bodyBytes)
|
||||
|
||||
if fields.model.Exists() {
|
||||
if fields.model.Type != gjson.String {
|
||||
return fmt.Errorf("invalid model field type")
|
||||
}
|
||||
parsed.Model = strings.Clone(modelResult.String())
|
||||
parsed.Model = strings.Clone(fields.model.String())
|
||||
if protocol == domain.PlatformAnthropic {
|
||||
normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model)
|
||||
if normalizedModel != parsed.Model {
|
||||
@@ -263,47 +350,46 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro
|
||||
}
|
||||
parsed.Body.Replace(normalizedBody)
|
||||
bodyBytes = normalizedBody
|
||||
jsonStr = *(*string)(unsafe.Pointer(&bodyBytes))
|
||||
// 改写后旧的值视图指向已失效的字节,重新遍历一次(仅 [1m] 规范化这条罕见路径)。
|
||||
fields = scanGatewayRequestRoot(bodyBytes)
|
||||
parsed.Model = normalizedModel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
streamResult := gjson.Get(jsonStr, "stream")
|
||||
if streamResult.Exists() {
|
||||
if streamResult.Type != gjson.True && streamResult.Type != gjson.False {
|
||||
if fields.stream.Exists() {
|
||||
if fields.stream.Type != gjson.True && fields.stream.Type != gjson.False {
|
||||
return fmt.Errorf("invalid stream field type")
|
||||
}
|
||||
parsed.Stream = streamResult.Bool()
|
||||
parsed.Stream = fields.stream.Bool()
|
||||
}
|
||||
|
||||
parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String())
|
||||
parsed.MetadataUserID = strings.Clone(fields.metadataUID.String())
|
||||
|
||||
thinkingType := gjson.Get(jsonStr, "thinking.type").String()
|
||||
thinkingType := fields.thinkingType.String()
|
||||
parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" ||
|
||||
(protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model))
|
||||
|
||||
parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()))
|
||||
parsed.OutputEffort = strings.Clone(strings.TrimSpace(fields.outputEffort.String()))
|
||||
if protocol == domain.PlatformAnthropic {
|
||||
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())))
|
||||
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(fields.speed.String())))
|
||||
}
|
||||
|
||||
maxTokensResult := gjson.Get(jsonStr, "max_tokens")
|
||||
if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number {
|
||||
f := maxTokensResult.Float()
|
||||
if fields.maxTokens.Exists() && fields.maxTokens.Type == gjson.Number {
|
||||
f := fields.maxTokens.Float()
|
||||
if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) &&
|
||||
f <= float64(math.MaxInt) && f >= float64(math.MinInt) {
|
||||
parsed.MaxTokens = int(f)
|
||||
}
|
||||
}
|
||||
|
||||
setGatewayRequestRanges(parsed, protocol, jsonStr)
|
||||
setGatewayRequestRangesFromFields(parsed, protocol, fields)
|
||||
parsed.saveBodyState()
|
||||
return nil
|
||||
}
|
||||
|
||||
func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error {
|
||||
return parseGatewayRequestCurrentBody(parsed, protocol)
|
||||
return parseGatewayRequestBody(parsed, protocol, true)
|
||||
}
|
||||
|
||||
// DescribeInvalidJSON returns a diagnostic error for a request body that
|
||||
@@ -410,8 +496,20 @@ func normalizeSessionUserAgentFallback(raw string) string {
|
||||
// protocol 指定请求协议格式(domain.PlatformAnthropic / domain.PlatformGemini),
|
||||
// 不同协议使用不同的 system/messages 字段名。
|
||||
func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) {
|
||||
return parseGatewayRequest(body, protocol, true)
|
||||
}
|
||||
|
||||
// ParseGatewayRequestValidated 与 ParseGatewayRequest 结果相同,但要求调用方已经确认
|
||||
// body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes,且此后的改写只
|
||||
// 经过 sjson)。它跳过这次全量校验——1 MiB body 上约 510µs,占解析耗时的七成。
|
||||
// 非法 JSON 的语义与未校验版本不同,只允许在校验过同一份字节的调用点使用。
|
||||
func ParseGatewayRequestValidated(body *RequestBodyRef, protocol string) (*ParsedRequest, error) {
|
||||
return parseGatewayRequest(body, protocol, false)
|
||||
}
|
||||
|
||||
func parseGatewayRequest(body *RequestBodyRef, protocol string, validate bool) (*ParsedRequest, error) {
|
||||
parsed := &ParsedRequest{Body: body}
|
||||
if err := parseGatewayRequestCurrentBody(parsed, protocol); err != nil {
|
||||
if err := parseGatewayRequestBody(parsed, protocol, validate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parsed, nil
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
)
|
||||
|
||||
// buildGatewayRequestBenchmarkBody 生成 Codex / Claude Code 两种形态的大请求体。
|
||||
func buildGatewayRequestBenchmarkBody(targetBytes int, anthropic bool) []byte {
|
||||
var sb strings.Builder
|
||||
sb.Grow(targetBytes + 1024)
|
||||
// strings.Builder.WriteString 的 error 恒为 nil,errcheck 不接受裸忽略,收口在这里。
|
||||
write := func(s string) { _, _ = sb.WriteString(s) }
|
||||
item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}`
|
||||
if anthropic {
|
||||
write(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`)
|
||||
write(strings.Repeat("z", targetBytes/8))
|
||||
write(`"}],"tools":[{"name":"shell","description":"`)
|
||||
write(strings.Repeat("y", targetBytes/16))
|
||||
write(`"}],"messages":[`)
|
||||
msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}`
|
||||
for i := 0; sb.Len() < targetBytes; i++ {
|
||||
if i > 0 {
|
||||
write(`,`)
|
||||
}
|
||||
write(msg)
|
||||
}
|
||||
write(`]}`)
|
||||
return []byte(sb.String())
|
||||
}
|
||||
write(`{"model":"gpt-5.5","stream":true,"instructions":"`)
|
||||
write(strings.Repeat("z", targetBytes/8))
|
||||
write(`","tools":[{"type":"function","name":"shell","description":"`)
|
||||
write(strings.Repeat("y", targetBytes/16))
|
||||
write(`"}],"input":[`)
|
||||
for i := 0; sb.Len() < targetBytes; i++ {
|
||||
if i > 0 {
|
||||
write(`,`)
|
||||
}
|
||||
write(item)
|
||||
}
|
||||
write(`]}`)
|
||||
return []byte(sb.String())
|
||||
}
|
||||
|
||||
func BenchmarkParseGatewayRequestScan(b *testing.B) {
|
||||
cases := []struct {
|
||||
name string
|
||||
size int
|
||||
protocol string
|
||||
anthropic bool
|
||||
}{
|
||||
{"responses_128KiB", 128 << 10, "responses", false},
|
||||
{"responses_1MiB", 1 << 20, "responses", false},
|
||||
{"anthropic_1MiB", 1 << 20, domain.PlatformAnthropic, true},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
body := buildGatewayRequestBenchmarkBody(tc.size, tc.anthropic)
|
||||
b.Run(tc.name+"/legacy", func(b *testing.B) {
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ReportAllocs()
|
||||
for range b.N {
|
||||
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
|
||||
if err := legacyParseGatewayRequestCurrentBody(parsed, tc.protocol); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.Run(tc.name+"/scan", func(b *testing.B) {
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ReportAllocs()
|
||||
for range b.N {
|
||||
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
|
||||
if err := parseGatewayRequestBody(parsed, tc.protocol, true); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
// 调用方已经校验过同一份字节时(handler 已做 gjson.ValidBytes,且之后只经 sjson 改写)。
|
||||
b.Run(tc.name+"/scan_validated", func(b *testing.B) {
|
||||
b.SetBytes(int64(len(body)))
|
||||
b.ReportAllocs()
|
||||
for range b.N {
|
||||
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
|
||||
if err := parseGatewayRequestBody(parsed, tc.protocol, false); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/domain"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
|
||||
// 下面两个函数是重构前的 parseGatewayRequestCurrentBody / setGatewayRequestRanges
|
||||
// 的逐字副本,作为差分测试的基准。任何一处语义变化都会在下面的对比里暴露。
|
||||
func legacyParseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error {
|
||||
if parsed == nil || parsed.Body == nil {
|
||||
return fmt.Errorf("empty request body")
|
||||
}
|
||||
parsed.Body.parsed = nil
|
||||
|
||||
bodyBytes := parsed.Body.Bytes()
|
||||
if !gjson.ValidBytes(bodyBytes) {
|
||||
return DescribeInvalidJSON(bodyBytes)
|
||||
}
|
||||
|
||||
jsonStr := *(*string)(unsafe.Pointer(&bodyBytes))
|
||||
clearGatewayRequestDerivedState(parsed)
|
||||
parsed.protocol = protocol
|
||||
|
||||
modelResult := gjson.Get(jsonStr, "model")
|
||||
if modelResult.Exists() {
|
||||
if modelResult.Type != gjson.String {
|
||||
return fmt.Errorf("invalid model field type")
|
||||
}
|
||||
parsed.Model = strings.Clone(modelResult.String())
|
||||
if protocol == domain.PlatformAnthropic {
|
||||
normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model)
|
||||
if normalizedModel != parsed.Model {
|
||||
normalizedBody, err := sjson.SetBytes(bodyBytes, "model", normalizedModel)
|
||||
if err != nil {
|
||||
return fmt.Errorf("normalize model field: %w", err)
|
||||
}
|
||||
parsed.Body.Replace(normalizedBody)
|
||||
bodyBytes = normalizedBody
|
||||
jsonStr = *(*string)(unsafe.Pointer(&bodyBytes))
|
||||
parsed.Model = normalizedModel
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
streamResult := gjson.Get(jsonStr, "stream")
|
||||
if streamResult.Exists() {
|
||||
if streamResult.Type != gjson.True && streamResult.Type != gjson.False {
|
||||
return fmt.Errorf("invalid stream field type")
|
||||
}
|
||||
parsed.Stream = streamResult.Bool()
|
||||
}
|
||||
|
||||
parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String())
|
||||
|
||||
thinkingType := gjson.Get(jsonStr, "thinking.type").String()
|
||||
parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" ||
|
||||
(protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model))
|
||||
|
||||
parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()))
|
||||
if protocol == domain.PlatformAnthropic {
|
||||
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())))
|
||||
}
|
||||
|
||||
maxTokensResult := gjson.Get(jsonStr, "max_tokens")
|
||||
if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number {
|
||||
f := maxTokensResult.Float()
|
||||
if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) &&
|
||||
f <= float64(math.MaxInt) && f >= float64(math.MinInt) {
|
||||
parsed.MaxTokens = int(f)
|
||||
}
|
||||
}
|
||||
|
||||
legacySetGatewayRequestRanges(parsed, protocol, jsonStr)
|
||||
parsed.saveBodyState()
|
||||
return nil
|
||||
}
|
||||
|
||||
func legacySetGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) {
|
||||
if parsed == nil {
|
||||
return
|
||||
}
|
||||
switch protocol {
|
||||
case domain.PlatformGemini:
|
||||
if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() {
|
||||
parsed.systemRange = rangeFromResult(sysParts)
|
||||
}
|
||||
if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(contents)
|
||||
}
|
||||
default:
|
||||
if sys := gjson.Get(jsonStr, "system"); sys.Exists() {
|
||||
parsed.HasSystem = true
|
||||
parsed.systemRange = rangeFromResult(sys)
|
||||
}
|
||||
if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() {
|
||||
parsed.messagesRange = rangeFromResult(msgs)
|
||||
}
|
||||
if protocol == "responses" {
|
||||
if input := gjson.Get(jsonStr, "input"); input.Exists() {
|
||||
parsed.inputRange = rangeFromResult(input)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parsedSnapshot 只记录解析产出的可观测结果,避免比较实现内部的缓存指针。
|
||||
type parsedSnapshot struct {
|
||||
err string
|
||||
model string
|
||||
stream bool
|
||||
metadataUserID string
|
||||
thinkingOn bool
|
||||
outputEffort string
|
||||
speed string
|
||||
maxTokens int
|
||||
hasSystem bool
|
||||
systemRange jsonRange
|
||||
messagesRange jsonRange
|
||||
inputRange jsonRange
|
||||
protocol string
|
||||
bodyAfter string
|
||||
}
|
||||
|
||||
func snapshotOf(parsed *ParsedRequest, err error) parsedSnapshot {
|
||||
snap := parsedSnapshot{}
|
||||
if err != nil {
|
||||
snap.err = err.Error()
|
||||
}
|
||||
if parsed == nil {
|
||||
return snap
|
||||
}
|
||||
snap.model = parsed.Model
|
||||
snap.stream = parsed.Stream
|
||||
snap.metadataUserID = parsed.MetadataUserID
|
||||
snap.thinkingOn = parsed.ThinkingEnabled
|
||||
snap.outputEffort = parsed.OutputEffort
|
||||
snap.speed = parsed.Speed
|
||||
snap.maxTokens = parsed.MaxTokens
|
||||
snap.hasSystem = parsed.HasSystem
|
||||
snap.systemRange = parsed.systemRange
|
||||
snap.messagesRange = parsed.messagesRange
|
||||
snap.inputRange = parsed.inputRange
|
||||
snap.protocol = parsed.protocol
|
||||
if parsed.Body != nil {
|
||||
snap.bodyAfter = string(parsed.Body.Bytes())
|
||||
}
|
||||
return snap
|
||||
}
|
||||
|
||||
func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, parsedSnapshot) {
|
||||
t.Helper()
|
||||
legacyBody := NewRequestBodyRef(append([]byte(nil), body...))
|
||||
legacyParsed := &ParsedRequest{Body: legacyBody}
|
||||
legacyErr := legacyParseGatewayRequestCurrentBody(legacyParsed, protocol)
|
||||
|
||||
// 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。
|
||||
newBody := NewRequestBodyRef(append([]byte(nil), body...))
|
||||
newParsed := &ParsedRequest{Body: newBody}
|
||||
newErr := parseGatewayRequestBody(newParsed, protocol, true)
|
||||
|
||||
return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr)
|
||||
}
|
||||
|
||||
func TestParseGatewayRequestMatchesLegacy(t *testing.T) {
|
||||
escape := string(rune(92))
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{"typical responses", `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`},
|
||||
{"typical anthropic", `{"model":"claude-sonnet-5-5","stream":true,"system":"s","messages":[{"role":"user","content":"hi"}],"max_tokens":1024,"thinking":{"type":"enabled"},"output_config":{"effort":" high "},"speed":"Fast"}`},
|
||||
{"typical gemini", `{"contents":[{"parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"sys"}]},"generationConfig":{"maxOutputTokens":32}}`},
|
||||
{"empty object", `{}`},
|
||||
{"empty string", ``},
|
||||
{"invalid json", `{"model":`},
|
||||
{"invalid json with image tool", `{"tools":[{"type":"image_generation"}]`},
|
||||
{"model wrong type", `{"model":123}`},
|
||||
{"model null", `{"model":null}`},
|
||||
{"stream wrong type", `{"model":"m","stream":"yes"}`},
|
||||
{"stream null", `{"model":"m","stream":null}`},
|
||||
{"stream false", `{"model":"m","stream":false}`},
|
||||
{"max_tokens float", `{"model":"m","max_tokens":1024.5}`},
|
||||
{"max_tokens negative", `{"model":"m","max_tokens":-8}`},
|
||||
{"max_tokens huge", `{"model":"m","max_tokens":1e30}`},
|
||||
{"max_tokens string", `{"model":"m","max_tokens":"1024"}`},
|
||||
{"metadata nested", `{"metadata":{"user_id":"u1"}}`},
|
||||
{"metadata string first", `{"metadata":"x","metadata":{"user_id":"u2"}}`},
|
||||
{"metadata null child", `{"metadata":{"user_id":null},"metadata":{"user_id":"u3"}}`},
|
||||
{"metadata wrong shape", `{"metadata":[],"metadata":{"user_id":"u4"}}`},
|
||||
{"thinking string first", `{"thinking":"x","thinking":{"type":"enabled"}}`},
|
||||
{"thinking adaptive", `{"thinking":{"type":"adaptive"}}`},
|
||||
{"thinking between tools", `{"thinking":{"type":"between_tools"}}`},
|
||||
{"effort with spaces", `{"output_config":{"effort":" medium "}}`},
|
||||
{"effort first empty", `{"output_config":{"effort":""},"output_config":{"effort":"high"}}`},
|
||||
{"speed uppercase", `{"speed":" FAST "}`},
|
||||
{"system string", `{"system":"sys","messages":[{"role":"user"}]}`},
|
||||
{"system object", `{"system":{"type":"text"},"messages":[]}`},
|
||||
{"system wrong shape", `{"system":123}`},
|
||||
{"messages not array", `{"messages":"x"}`},
|
||||
{"input present", `{"input":[{"a":1}]}`},
|
||||
{"contents not array", `{"contents":"x"}`},
|
||||
{"gemini parts not array", `{"systemInstruction":{"parts":"x"}}`},
|
||||
{"gemini parts retry", `{"systemInstruction":{"parts":"x"},"systemInstruction":{"parts":[{"a":1}]}}`},
|
||||
{"duplicate model", `{"model":"m1","model":"m2"}`},
|
||||
{"duplicate stream", `{"stream":true,"stream":false}`},
|
||||
{"long context suffix", `{"model":"claude-sonnet-5-5[1m]","messages":[]}`},
|
||||
{"long context suffix duplicated", `{"model":"claude-sonnet-5-5[1m][1m]","messages":[]}`},
|
||||
{"escaped system key", `{"` + escape + `u0073ystem":"s","messages":[]}`},
|
||||
{"escaped model key", `{"` + escape + `u006dodel":"m"}`},
|
||||
{"root array", `[1,2,3]`},
|
||||
{"root scalar", `"just a string"`},
|
||||
{"nested nulls", `{"model":"m","system":null,"messages":[{"a":1}],"input":null}`},
|
||||
{"unicode content", `{"model":"m","messages":[{"content":"中文 😀"}]}`},
|
||||
}
|
||||
|
||||
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
|
||||
|
||||
for _, tc := range cases {
|
||||
for _, protocol := range protocols {
|
||||
t.Run(tc.name+"/"+protocol, func(t *testing.T) {
|
||||
want, got := parseBoth(t, protocol, []byte(tc.body))
|
||||
require.Equal(t, want, got, "body=%s", tc.body)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// deterministic 随机组合,覆盖键顺序、重复键、类型混杂的组合空间。
|
||||
func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) {
|
||||
pieces := []string{
|
||||
`"model":"m"`, `"model":"claude-x[1m]"`, `"model":null`, `"model":1`,
|
||||
`"stream":true`, `"stream":"x"`, `"stream":null`,
|
||||
`"max_tokens":16`, `"max_tokens":16.5`, `"max_tokens":"16"`,
|
||||
`"metadata":{"user_id":"u"}`, `"metadata":"s"`, `"metadata":null`,
|
||||
`"thinking":{"type":"enabled"}`, `"thinking":{"type":"adaptive"}`, `"thinking":"x"`,
|
||||
`"output_config":{"effort":" low "}`, `"output_config":null`,
|
||||
`"speed":" FAST "`, `"speed":null`,
|
||||
`"system":"sys"`, `"system":[{"type":"text"}]`, `"system":null`,
|
||||
`"messages":[]`, `"messages":[{"role":"user"}]`, `"messages":"x"`,
|
||||
`"input":[]`, `"input":[{"a":1}]`, `"input":null`,
|
||||
`"contents":[]`, `"contents":"x"`,
|
||||
`"systemInstruction":{"parts":[]}`, `"systemInstruction":{"parts":"x"}`,
|
||||
`"unknown":1`, `"unknown":{"nested":true}`,
|
||||
}
|
||||
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
|
||||
|
||||
seed := uint64(0x9e3779b97f4a7c15)
|
||||
next := func() uint64 {
|
||||
seed ^= seed << 13
|
||||
seed ^= seed >> 7
|
||||
seed ^= seed << 17
|
||||
return seed
|
||||
}
|
||||
|
||||
for i := 0; i < 3000; i++ {
|
||||
n := int(next()%6) + 1
|
||||
parts := make([]string, 0, n)
|
||||
for j := 0; j < n; j++ {
|
||||
parts = append(parts, pieces[int(next()%uint64(len(pieces)))])
|
||||
}
|
||||
body := []byte("{" + strings.Join(parts, ",") + "}")
|
||||
protocol := protocols[int(next()%uint64(len(protocols)))]
|
||||
|
||||
want, got := parseBoth(t, protocol, body)
|
||||
require.Equal(t, want, got, "iteration=%d protocol=%s body=%s", i, protocol, body)
|
||||
}
|
||||
}
|
||||
|
||||
// 已校验变体只允许在「body 合法」的前提下使用;合法 JSON 上两者必须产出完全相同的结果。
|
||||
func TestParseGatewayRequestValidatedMatchesValidatingPath(t *testing.T) {
|
||||
bodies := []string{
|
||||
`{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`,
|
||||
`{"model":"claude-x[1m]","messages":[],"system":"s","max_tokens":8}`,
|
||||
`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"},"output_config":{"effort":" high "}}`,
|
||||
`{"contents":[],"systemInstruction":{"parts":[]}}`,
|
||||
`{}`,
|
||||
}
|
||||
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
|
||||
for _, body := range bodies {
|
||||
for _, protocol := range protocols {
|
||||
validating := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))}
|
||||
validatingErr := parseGatewayRequestBody(validating, protocol, true)
|
||||
|
||||
trusted := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))}
|
||||
trustedErr := parseGatewayRequestBody(trusted, protocol, false)
|
||||
|
||||
require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr),
|
||||
"body=%s protocol=%s", body, protocol)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) {
|
||||
f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses")
|
||||
f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic)
|
||||
f.Add([]byte(`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"}}`), "chat_completions")
|
||||
f.Add([]byte(`{"contents":[],"systemInstruction":{"parts":[]}}`), domain.PlatformGemini)
|
||||
f.Fuzz(func(t *testing.T, body []byte, protocol string) {
|
||||
switch protocol {
|
||||
case "responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini:
|
||||
default:
|
||||
return
|
||||
}
|
||||
want, got := parseBoth(t, protocol, body)
|
||||
require.Equal(t, want, got, "body=%q protocol=%s", body, protocol)
|
||||
|
||||
// 合法 JSON 上,跳过校验不得改变结果。
|
||||
if gjson.ValidBytes(body) {
|
||||
validating := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))}
|
||||
validatingErr := parseGatewayRequestBody(validating, protocol, true)
|
||||
trusted := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))}
|
||||
trustedErr := parseGatewayRequestBody(trusted, protocol, false)
|
||||
require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr),
|
||||
"validated path diverged: body=%q protocol=%s", body, protocol)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user