Files
CLIProxyAPI/internal/runtime/executor/helps/payload_query_eval.go
sususu98 40beca02c8 perf(payload,handlers): eliminate large base64 allocation amplification
Avoid full-payload copies when evaluating payload rules and reading HTTP
request bodies, cutting heap allocation amplification on multi-megabyte
base64 requests by >80% with zero behavioral changes:

- Evaluate single-item payload query predicates directly on ojson.Result
  without copying item.Raw into a temporary "[...]" buffer (with exact
  fallback for edge/malformed syntax).
- Resolve clean array "@reverse.<N>" paths via zero-copy ForEach traversal
  instead of ojson.modReverse full-array cloning.
- Fast-path scalar, empty-container ([] / {}), and type-mismatch checks in
  payloadResultEquals to skip moego/json.Unmarshal on large arrays, and use
  bytes.TrimSpace in normalizedPayloadJSON.
- Cache compiled moego/regexp patterns in payload.replace with a bounded map.
- Release originalRequest in ClaudeInputTokenState once disabled or handled,
  and only retain replayRequestPayload in Antigravity stream when replayScope
  is valid.
- Preallocate raw request body buffers from Content-Length (capped at 4 MiB)
  in ReadRawRequestBody to avoid io.ReadAll slice-doubling copies.
2026-11-29 12:22:41 +08:00

617 lines
13 KiB
Go

package helps
import (
"encoding"
"reflect"
"strconv"
"strings"
"unicode/utf8"
"github.com/MoeForge/moego/json"
"github.com/MoeForge/moego/ojson"
)
type parsedPayloadQueryTerm struct {
path string
op string
val string
}
func payloadQueryTermMatches(item ojson.Result, term string) bool {
term = strings.TrimSpace(term)
if term == "" || item.Raw == "" {
return false
}
q, ok := parsePayloadQueryTerm(term)
if !ok {
return payloadQueryTermMatchesFallback(item, term)
}
qv := item
if item.Type == ojson.JSON {
qv = item.Get(q.path)
} else if q.path != "" {
return false
}
return payloadQueryMatchValue(q.op, q.val, qv)
}
func payloadQueryTermMatchesFallback(item ojson.Result, term string) bool {
term = strings.TrimSpace(term)
if term == "" || item.Raw == "" {
return false
}
wrapped := make([]byte, 0, len(item.Raw)+2)
wrapped = append(wrapped, '[')
wrapped = append(wrapped, item.Raw...)
wrapped = append(wrapped, ']')
return ojson.GetBytesNoCopy(wrapped, "#("+term+")").Exists()
}
// parsePayloadQueryTerm mirrors moego/ojson's "#(...)" query parser so single-item
// predicates evaluate directly against item without copying item.Raw into "[...]".
func parsePayloadQueryTerm(term string) (parsedPayloadQueryTerm, bool) {
var q parsedPayloadQueryTerm
depth, opAt, vesc := 1, -1, false
for i := 0; i < len(term); i++ {
ch := term[i]
if depth == 1 && opAt < 0 {
switch ch {
case '!', '=', '<', '>', '%':
opAt = i
continue
}
}
switch ch {
case '\\':
if i+1 >= len(term) {
// Trailing backslash escapes the closing ')' in "#("+term+")".
return parsedPayloadQueryTerm{}, false
}
i++
case '(', '[':
depth++
case ')', ']':
depth--
if depth == 0 {
// Premature closing bracket inside term: fall back to ojson.
return parsedPayloadQueryTerm{}, false
}
case '"':
closed := false
for i++; i < len(term); i++ {
if term[i] == '\\' {
vesc = true
i++
} else if term[i] == '"' {
closed = true
break
}
}
if !closed {
return parsedPayloadQueryTerm{}, false
}
}
}
if depth != 1 {
return parsedPayloadQueryTerm{}, false
}
if opAt < 0 {
q.path = trimPayloadQuerySpace(term)
return q, true
}
q.path = trimPayloadQuerySpace(term[:opAt])
v := trimPayloadQuerySpace(term[opAt:])
n := 1
switch {
case len(v) == 1:
case v[1] == '=' && (v[0] == '!' || v[0] == '<' || v[0] == '>'), v[0] == '!' && v[1] == '%':
n = 2
case v[0] == '=' && v[1] == '=':
v = v[1:]
case v[0] == '!':
n = 0
}
q.op, v = v[:n], trimPayloadQuerySpace(v[n:])
if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' {
inner := v[1 : len(v)-1]
if vesc {
for k := 0; k < len(inner); k++ {
if inner[k] < ' ' {
// Raw control bytes in escaped query strings: fall back for byte-exact parity.
return parsedPayloadQueryTerm{}, false
}
}
if !ojson.Valid(v) {
return parsedPayloadQueryTerm{}, false
}
parsed := ojson.Parse(v)
if parsed.Type != ojson.String {
return parsedPayloadQueryTerm{}, false
}
v = parsed.Str
} else {
v = inner
}
}
q.val = v
return q, true
}
func trimPayloadQuerySpace(s string) string {
for len(s) > 0 && s[0] <= ' ' {
s = s[1:]
}
for len(s) > 0 && s[len(s)-1] <= ' ' {
s = s[:len(s)-1]
}
return s
}
func payloadQueryMatchValue(op, val string, v ojson.Result) bool {
if len(val) > 0 && val[0] == '~' {
var ish bool
switch val[1:] {
case "*":
ish = v.Exists()
case "null":
ish = v.Type == ojson.Null
case "true":
ish = payloadQueryTruthy(v)
case "false":
ish = payloadQueryFalsy(v)
default:
return false
}
val = "true"
v = ojson.Result{Type: ojson.False}
if ish {
v.Type = ojson.True
}
}
if !v.Exists() {
return false
}
if op == "" {
return true
}
switch v.Type {
case ojson.String:
switch op {
case "=":
return v.Str == val
case "!=":
return v.Str != val
case "<":
return v.Str < val
case "<=":
return v.Str <= val
case ">":
return v.Str > val
case ">=":
return v.Str >= val
case "%":
return payloadQueryGlobMatch(v.Str, val)
case "!%":
return !payloadQueryGlobMatch(v.Str, val)
}
case ojson.Number:
n, _ := strconv.ParseFloat(val, 64)
switch op {
case "=":
return v.Num == n
case "!=":
return v.Num != n
case "<":
return v.Num < n
case "<=":
return v.Num <= n
case ">":
return v.Num > n
case ">=":
return v.Num >= n
}
case ojson.True:
switch op {
case "=":
return val == "true"
case "!=":
return val != "true"
case ">":
return val == "false"
case ">=":
return true
}
case ojson.False:
switch op {
case "=":
return val == "false"
case "!=":
return val != "false"
case "<":
return val == "true"
case "<=":
return true
}
}
return false
}
func payloadQueryTruthy(v ojson.Result) bool {
switch v.Type {
case ojson.True:
return true
case ojson.String:
b, err := strconv.ParseBool(v.Str)
return err == nil && b
case ojson.Number:
return v.Num != 0
}
return false
}
func payloadQueryFalsy(v ojson.Result) bool {
switch v.Type {
case ojson.Null, ojson.False:
return true
case ojson.String:
b, err := strconv.ParseBool(v.Str)
return err == nil && !b
case ojson.Number:
return v.Num == 0
}
return false
}
func payloadQueryGlobMatch(s, pattern string) bool {
si, pi := 0, 0
starP, starS := -1, 0
for {
if pi < len(pattern) {
switch pattern[pi] {
case '*':
starP, starS = pi, si
pi++
continue
case '?':
if si < len(s) {
_, n := utf8.DecodeRuneInString(s[si:])
si += n
pi++
continue
}
case '\\':
if pi+1 < len(pattern) && si < len(s) {
if n, m := payloadQuerySameRune(s, si, pattern, pi+1); n > 0 {
si += n
pi += 1 + m
continue
}
}
default:
if si < len(s) {
if n, m := payloadQuerySameRune(s, si, pattern, pi); n > 0 {
si += n
pi += m
continue
}
}
}
} else if si == len(s) {
return true
}
if starP < 0 || starS >= len(s) {
return false
}
_, n := utf8.DecodeRuneInString(s[starS:])
starS += n
si, pi = starS, starP+1
}
}
func payloadQuerySameRune(s string, i int, p string, j int) (n, m int) {
if c, d := s[i], p[j]; c < utf8.RuneSelf || d < utf8.RuneSelf {
if c == d {
return 1, 1
}
return 0, 0
}
r, n := utf8.DecodeRuneInString(s[i:])
q, m := utf8.DecodeRuneInString(p[j:])
if r != q {
return 0, 0
}
return n, m
}
// payloadGetPathDoc resolves path against doc while avoiding ojson.modReverse
// full-array allocations for "@reverse.<index>" lookups on JSON arrays.
func payloadGetPathDoc(doc *ojson.Doc, path string) ojson.Result {
if doc == nil {
return ojson.Result{}
}
if !strings.Contains(path, "@reverse") {
return doc.Get(path)
}
return payloadGetPathWithReverseFastPath(doc.Get, path)
}
func payloadGetPathBytes(payload []byte, path string) ojson.Result {
if !strings.Contains(path, "@reverse") {
return ojson.GetBytesNoCopy(payload, path)
}
return payloadGetPathWithReverseFastPath(func(p string) ojson.Result {
return payloadValueAtPath(payload, p)
}, path)
}
func payloadGetPathWithReverseFastPath(get func(string) ojson.Result, path string) ojson.Result {
// Only optimize clean dotted paths without pipes, multipaths, or modifier arguments.
if strings.ContainsAny(path, "|{[") {
return get(path)
}
prefix, indexPart, rest, ok := splitPayloadReverseSegment(path)
if !ok {
return get(path)
}
// Projections, queries, wildcards, modifiers, or escapes in prefix can map
// "@reverse" across multiple elements; fall back to exact ojson evaluation.
if strings.ContainsAny(prefix, "#*?@\\") {
return get(path)
}
tailOffset, ok := parseNonNegativeDecimalIndex(indexPart)
if !ok || tailOffset > 64 {
return get(path)
}
var node ojson.Result
if prefix == "" {
node = get("@this")
} else {
node = get(prefix)
}
if !node.IsArray() {
// Objects and non-arrays retain exact ojson @reverse semantics.
return get(path)
}
elem, found := payloadArrayElementFromEnd(node, tailOffset)
if !found {
return ojson.Result{}
}
if rest == "" {
return elem
}
if strings.Contains(rest, "@reverse") {
return payloadGetPathWithReverseFastPath(elem.Get, rest)
}
if strings.Contains(rest, "@") {
return get(path)
}
return elem.Get(rest)
}
// splitPayloadReverseSegment splits a dotted path around the first top-level
// "@reverse.<index>" segment without allocating slices or joined strings.
func splitPayloadReverseSegment(path string) (prefix, indexPart, rest string, ok bool) {
depth := 0
var quote byte
escaped := false
segStart := 0
revSegStart := -1
for i := 0; i <= len(path); i++ {
if i < len(path) {
ch := path[i]
if escaped {
escaped = false
continue
}
if ch == '\\' {
escaped = true
continue
}
if quote != 0 {
if ch == quote {
quote = 0
}
continue
}
if ch == '"' || ch == '\'' {
quote = ch
continue
}
if ch == '(' {
depth++
continue
}
if ch == ')' && depth > 0 {
depth--
continue
}
if ch != '.' || depth != 0 {
continue
}
}
seg := path[segStart:i]
if revSegStart >= 0 {
if revSegStart > 0 {
prefix = path[:revSegStart-1]
}
indexPart = seg
if i < len(path) {
if i+1 == len(path) {
// Trailing dot after index (e.g. "@reverse.0."): fall back to ojson.
return "", "", "", false
}
rest = path[i+1:]
}
return prefix, indexPart, rest, true
}
if seg == "@reverse" {
revSegStart = segStart
}
segStart = i + 1
}
return "", "", "", false
}
func parseNonNegativeDecimalIndex(part string) (int, bool) {
if part == "" {
return 0, false
}
for i := 0; i < len(part); i++ {
if part[i] < '0' || part[i] > '9' {
return 0, false
}
}
n, err := strconv.Atoi(part)
if err != nil || n < 0 {
return 0, false
}
return n, true
}
func payloadArrayElementFromEnd(arr ojson.Result, offsetFromEnd int) (ojson.Result, bool) {
if offsetFromEnd == 0 {
var last ojson.Result
found := false
arr.ForEach(func(_, item ojson.Result) bool {
last = item
found = true
return true
})
return last, found
}
size := offsetFromEnd + 1
ring := make([]ojson.Result, size)
count := 0
arr.ForEach(func(_, item ojson.Result) bool {
ring[count%size] = item
count++
return true
})
if count <= offsetFromEnd {
return ojson.Result{}, false
}
return ring[(count-1-offsetFromEnd)%size], true
}
// payloadResultEqualsFast handles scalar, empty-container, and type-mismatch checks
// without copying or unmarshaling large JSON subtrees (e.g. MB-scale base64 contents).
func payloadResultEqualsFast(result ojson.Result, value any) (equal bool, handled bool) {
if !result.Exists() {
return false, true
}
if value == nil {
return result.Type == ojson.Null && strings.TrimSpace(result.Raw) == "null", true
}
switch typed := value.(type) {
case bool:
if typed {
return result.Type == ojson.True, true
}
return result.Type == ojson.False, true
case string:
if result.Type != ojson.String {
return false, true
}
if result.Raw != "" && strings.IndexByte(result.Raw, '\\') < 0 && utf8.ValidString(result.Str) && utf8.ValidString(typed) {
if result.Str != typed {
return false, true
}
return !payloadRawHasControlByte(result.Raw), true
}
return false, false
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
if result.Type != ojson.Number {
return false, true
}
return false, false
}
if hasCustomJSONMarshaler(value) {
return false, false
}
rv := reflect.ValueOf(value)
switch rv.Kind() {
case reflect.Slice:
if rv.Type().Elem().Kind() == reflect.Uint8 {
return false, false
}
if rv.IsNil() {
return result.Type == ojson.Null && strings.TrimSpace(result.Raw) == "null", true
}
if !result.IsArray() {
return false, true
}
if rv.Len() == 0 && result.Raw != "" {
return payloadRawIsEmptyJSONContainer(result.Raw, '[', ']'), true
}
case reflect.Array:
if rv.Type().Elem().Kind() == reflect.Uint8 {
return false, false
}
if !result.IsArray() {
return false, true
}
if rv.Len() == 0 && result.Raw != "" {
return payloadRawIsEmptyJSONContainer(result.Raw, '[', ']'), true
}
case reflect.Map:
if rv.Type().Key().Kind() != reflect.String {
return false, false
}
if rv.IsNil() {
return result.Type == ojson.Null && strings.TrimSpace(result.Raw) == "null", true
}
if !result.IsObject() {
return false, true
}
if rv.Len() == 0 && result.Raw != "" {
return payloadRawIsEmptyJSONContainer(result.Raw, '{', '}'), true
}
}
return false, false
}
func hasCustomJSONMarshaler(value any) bool {
if _, ok := value.(json.Marshaler); ok {
return true
}
if _, ok := value.(encoding.TextMarshaler); ok {
return true
}
return false
}
func payloadRawIsEmptyJSONContainer(raw string, openByte, closeByte byte) bool {
i := 0
for i < len(raw) && isJSONSpace(raw[i]) {
i++
}
if i >= len(raw) || raw[i] != openByte {
return false
}
i++
for i < len(raw) && isJSONSpace(raw[i]) {
i++
}
if i >= len(raw) || raw[i] != closeByte {
return false
}
i++
for i < len(raw) && isJSONSpace(raw[i]) {
i++
}
return i == len(raw)
}
func isJSONSpace(ch byte) bool {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
}
func payloadRawHasControlByte(raw string) bool {
for i := 0; i < len(raw); i++ {
if raw[i] < 0x20 {
return true
}
}
return false
}