Each request ran ~45 bytes.Contains over its whole body to ask whether
a key is there at all ("developer", "compaction, "display", the
passthrough key...). Most needles begin with a quote, JSON's commonest
byte, so bytes.Index stopped at every quote, gave up on that and
compared at every byte: on a 2 MB body ~9 ms a request, 36% of the
gateway's CPU in BenchmarkLargeRequest's profile.
bodyHas/bodyIndex find the needle's rarest byte (a static rank of the
bytes JSON, English and code use most) with IndexByte and compare the
needle only there; a needle of common bytes only hands the rest to
strings.Index after 64 misses, so it is never slower than before, and
it allocates nothing (a []byte(sep) of a needle over 32 bytes did).
148 literal and constant needles in internal/gateway use it, and
mayHoldHEIC's "eXB" walk uses bodyIndex.
mayHoldOddBase64 walked every byte through a switch (~2 ms a 2 MB
body); a run it looks for ends a string, so it now looks back from each
quote with a class table and gives the same answer.
Run on mica (Apple M6) at this tree:
- BenchmarkBodyHas, 7 needles over a 2 MB body: 4.43 ms -> 0.38 ms,
0 allocs (was 1).
- BenchmarkLargeRequest -benchtime 200x, before -> after:
anthropic 31.2 -> 28.9 ms, anthropic-group 31.4 -> 27.8,
chat 35.7 -> 32.8, responses 39.8 -> 29.8.
- go vet ./internal/gateway; gofmt -l clean.
- go test ./internal/gateway -count 1 -timeout 45m: ok (858s).
- Broken by hand: bodyIndex's start off by one -> TestBodyIndexIsIndex
red (wrong index on 5 needles and the random bodies); the URL-safe
class never counted -> TestOddBase64LooksAsItWalked red. Both green
again restored.
TestBodyIndexIsIndex holds bodyIndex to bytes.Index on a large
conversation and 3000 random bodies of common and rare bytes;
TestOddBase64LooksAsItWalked holds the new check to the old byte walk
(kept in the test) on 20000 random bodies and the three protocols'
large conversations.
Real account: the built app (mote, sandbox HOME) sent a 6KB request to
DeepSeek on /v1/responses and /v1/messages, both 200 "pong". Not
tried: Codex (the sandbox's sign-in is stale, and renewing it there
would rotate the live refresh token).
193 lines
5.8 KiB
Go
193 lines
5.8 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/tidwall/gjson"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// Google's Python SDK (google-genai) writes a part's bytes with
|
|
// base64.urlsafe_b64encode, '-' and '_' where standard base64 has '+' and
|
|
// '/', and Google's own API reads either. A vendor or relay behind magpie
|
|
// may read only the standard alphabet: dludream's image through a Gemini
|
|
// provider came back 400 "Failed to base64-decode image data", the same
|
|
// request with '+' and '/' answered (#5697). Every place in magpie that
|
|
// reads an image's bytes (HEIC and webp conversion, resizing, describing,
|
|
// token counts) read them as standard base64 too, and passed over one it
|
|
// couldn't. stdBase64Body writes the inline base64 a client sends as
|
|
// standard, padded base64 before anything reads the body, so every route
|
|
// has it so: a provider's own protocol passed through, one translated to,
|
|
// a plugin's fetch. Base64 that is standard and padded already is left as
|
|
// it came, byte for byte.
|
|
|
|
// stdBase64 is s as standard, padded base64 (RFC 4648 §4) when it is the
|
|
// URL-safe alphabet (§5) or unpadded; ok is false when s is standard and
|
|
// padded already, or isn't base64 of either alphabet (it then goes as it
|
|
// came, and the vendor says what it says of it).
|
|
func stdBase64(s string) (string, bool) {
|
|
if s == "" {
|
|
return s, false
|
|
}
|
|
urlSafe := strings.ContainsAny(s, "-_")
|
|
if !urlSafe && len(s)%4 == 0 {
|
|
return s, false
|
|
}
|
|
if urlSafe && strings.ContainsAny(s, "+/") {
|
|
return s, false // both alphabets: neither's
|
|
}
|
|
enc := base64.RawStdEncoding
|
|
if urlSafe {
|
|
enc = base64.RawURLEncoding
|
|
}
|
|
raw, err := enc.DecodeString(strings.TrimRight(s, "="))
|
|
if err != nil {
|
|
return s, false
|
|
}
|
|
return base64.StdEncoding.EncodeToString(raw), true
|
|
}
|
|
|
|
// mayHoldOddBase64 is whether body may hold base64 stdBase64 would write
|
|
// again, read in place: a run of at least 64 base64 characters (of either
|
|
// alphabet) ending a JSON string, with '-' or '_' in it or a length that
|
|
// isn't a multiple of four. Standard base64 of an image has '+' or '/'
|
|
// every few dozen characters, which ends a URL-safe run, and prose has
|
|
// spaces; a body it says yes to wrongly is only walked for nothing.
|
|
//
|
|
// It looks back from each quote, not at every byte: a run ends a string
|
|
// only there, and prose stops the look a word back. Its byte-by-byte walk
|
|
// took ~2 ms of each 2 MB request (BenchmarkLargeRequest).
|
|
func mayHoldOddBase64(body []byte) bool {
|
|
const least = 64
|
|
for i := 0; ; i++ {
|
|
q := bytes.IndexByte(body[i:], '"')
|
|
if q < 0 {
|
|
return false
|
|
}
|
|
i += q
|
|
start, odd := i, false
|
|
for start > 0 {
|
|
k := base64Class[body[start-1]]
|
|
if k == 0 {
|
|
break
|
|
}
|
|
odd = odd || k == 2
|
|
start--
|
|
}
|
|
if i-start >= least && (odd || (i-start)%4 != 0) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
// base64Class is 1 for a byte of standard base64 (with '='), 2 for one
|
|
// only URL-safe base64 has, 0 for the rest.
|
|
var base64Class = func() (t [256]uint8) {
|
|
for _, c := range []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") {
|
|
t[c] = 1
|
|
}
|
|
t['-'], t['_'] = 2, 2
|
|
return t
|
|
}()
|
|
|
|
// stdBase64Body is the body with each image's inline base64, and each
|
|
// Gemini inlineData part's whatever its type (a PDF, a recording), written
|
|
// as standard, padded base64; the body as it came when there is none.
|
|
func stdBase64Body(proto provider.Protocol, body []byte) []byte {
|
|
if !mayHoldOddBase64(body) {
|
|
return body
|
|
}
|
|
if proto == provider.Gemini {
|
|
return geminiStdBase64(body)
|
|
}
|
|
out, err := walkImages(proto, body, func(im imageAt) (json.RawMessage, error) {
|
|
rest, ok := strings.CutPrefix(im.Src, "data:")
|
|
if !ok {
|
|
return nil, nil
|
|
}
|
|
head, b64, ok := strings.Cut(rest, ",")
|
|
mime, isB64 := strings.CutSuffix(head, ";base64")
|
|
if !ok || !isB64 {
|
|
return nil, nil
|
|
}
|
|
std, ok := stdBase64(b64)
|
|
if !ok {
|
|
return nil, nil
|
|
}
|
|
return withImageData(proto, im.Block, mime, std), nil
|
|
})
|
|
if err != nil {
|
|
return body
|
|
}
|
|
return out
|
|
}
|
|
|
|
// geminiStdBase64 writes every inlineData part's data of a Gemini request
|
|
// (a turn's, a function response's, the system instruction's) as standard
|
|
// base64, in place: the rest of the body keeps its bytes.
|
|
func geminiStdBase64(body []byte) []byte {
|
|
if !gjson.ValidBytes(body) {
|
|
return body
|
|
}
|
|
type edit struct {
|
|
at, end int
|
|
raw, with string
|
|
}
|
|
var edits []edit
|
|
var parts func(gjson.Result)
|
|
parts = func(list gjson.Result) {
|
|
list.ForEach(func(_, part gjson.Result) bool {
|
|
for _, k := range []string{"inlineData", "inline_data"} {
|
|
d := part.Get(k + ".data")
|
|
if d.Type != gjson.String || d.Index <= 0 {
|
|
continue
|
|
}
|
|
if std, ok := stdBase64(d.Str); ok {
|
|
q, _ := json.Marshal(std)
|
|
edits = append(edits, edit{d.Index, d.Index + len(d.Raw), d.Raw, string(q)})
|
|
}
|
|
}
|
|
for _, k := range []string{"functionResponse", "function_response"} {
|
|
if fr := part.Get(k + ".parts"); fr.IsArray() {
|
|
parts(fr)
|
|
}
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
root := gjson.ParseBytes(body)
|
|
root.Get("contents").ForEach(func(_, turn gjson.Result) bool {
|
|
parts(turn.Get("parts"))
|
|
return true
|
|
})
|
|
for _, k := range []string{"systemInstruction", "system_instruction"} {
|
|
parts(root.Get(k + ".parts"))
|
|
}
|
|
if len(edits) == 0 {
|
|
return body
|
|
}
|
|
// the system instruction may come before the turns or after them;
|
|
// each edit is checked to be where gjson placed it
|
|
sort.Slice(edits, func(i, j int) bool { return edits[i].at < edits[j].at })
|
|
out := make([]byte, 0, len(body))
|
|
last := 0
|
|
for _, e := range edits {
|
|
if e.at < last || e.end > len(body) || string(body[e.at:e.end]) != e.raw {
|
|
return body // overlapping, as a key spelled twice: as it came
|
|
}
|
|
out = append(out, body[last:e.at]...)
|
|
out = append(out, e.with...)
|
|
last = e.end
|
|
}
|
|
out = append(out, body[last:]...)
|
|
if !json.Valid(out) {
|
|
return body
|
|
}
|
|
return out
|
|
}
|