mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(gemini): bound upstream SSE lines and antigravity non-stream reads
The Gemini native, Claude-compat, Chat Completions-compat and stream collector paths read upstream SSE with bufio.Reader.ReadString, so a custom base_url upstream that never sends a newline could grow one line without limit. - Read these streams through boundedSSELineReader, which keeps line endings and EOF semantics and enforces the configured line and event limits. An overflow is a stream read error; no truncated prefix is forwarded. - Thread cfg into collectGeminiSSE/collectGeminiSSEObserved. - Antigravity ForwardUpstream reads non-stream responses with ReadUpstreamResponseBody instead of an unlimited io.ReadAll. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9bb073d0d1
commit
d446c4a6bb
6 files changed
+83
-19
No files matched your search
@@ -6,7 +6,6 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -124,7 +123,7 @@ func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.
|
||||
clientDisconnect = streamRes.clientDisconnect
|
||||
} else {
|
||||
// 非流式响应:直接透传
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
respBody, err := ReadUpstreamResponseBody(resp.Body, s.antigravitySSEConfig(), c, anthropicTooLargeError)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read upstream response: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
@@ -266,7 +265,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions(
|
||||
clientDisconnect = streamRes.clientDisconnect
|
||||
streamFinished = streamRes.finished
|
||||
} else if useUpstreamStream {
|
||||
collected, usageObj, err := collectGeminiSSE(resp.Body, account.Type == AccountTypeOAuth)
|
||||
collected, usageObj, err := collectGeminiSSE(s.cfg, resp.Body, account.Type == AccountTypeOAuth)
|
||||
if err != nil {
|
||||
return nil, s.writeChatCompletionsError(c, http.StatusBadGateway, "upstream_error", "Failed to read upstream stream")
|
||||
}
|
||||
@@ -623,9 +622,9 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom
|
||||
return disconnected
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
reader := newBoundedSSELineReader(resp.Body, s.cfg)
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
line, err := reader.ReadLineString()
|
||||
if len(line) > 0 {
|
||||
trimmed := strings.TrimRight(line, "\r\n")
|
||||
if strings.HasPrefix(trimmed, "data:") {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
@@ -1034,7 +1033,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
|
||||
streamFinished = streamRes.finished
|
||||
} else {
|
||||
if useUpstreamStream {
|
||||
collected, usageObj, err := collectGeminiSSE(resp.Body, true)
|
||||
collected, usageObj, err := collectGeminiSSE(s.cfg, resp.Body, true)
|
||||
if err != nil {
|
||||
return nil, s.writeClaudeError(c, http.StatusBadGateway, "upstream_error", "Failed to read upstream stream")
|
||||
}
|
||||
@@ -1565,7 +1564,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
|
||||
} else {
|
||||
if useUpstreamStream {
|
||||
var best geminiResponseSignal
|
||||
collected, usageObj, stats, err := collectGeminiSSEObserved(resp.Body, isOAuth, func(rawBytes []byte) {
|
||||
collected, usageObj, stats, err := collectGeminiSSEObserved(s.cfg, resp.Body, isOAuth, func(rawBytes []byte) {
|
||||
if sig, ok := detectGeminiResponseSignal(rawBytes); ok && sig.Kind > best.Kind {
|
||||
best = sig
|
||||
}
|
||||
@@ -2217,9 +2216,9 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re
|
||||
openToolName := ""
|
||||
seenToolJSON := ""
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
reader := newBoundedSSELineReader(resp.Body, s.cfg)
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
line, err := reader.ReadLineString()
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
if geminiStreamAbortedWithBillableOutput(c, err, &usage) {
|
||||
logger.LegacyPrintf("service.gemini_messages_compat", "[GeminiAPI] Client disconnected during messages stream, billing collected usage: %v", err)
|
||||
@@ -2566,8 +2565,8 @@ func unwrapIfNeeded(isOAuth bool, raw []byte) []byte {
|
||||
return inner
|
||||
}
|
||||
|
||||
func collectGeminiSSE(body io.Reader, isOAuth bool) (map[string]any, *ClaudeUsage, error) {
|
||||
collected, usage, _, err := collectGeminiSSEObserved(body, isOAuth, nil)
|
||||
func collectGeminiSSE(cfg *config.Config, body io.Reader, isOAuth bool) (map[string]any, *ClaudeUsage, error) {
|
||||
collected, usage, _, err := collectGeminiSSEObserved(cfg, body, isOAuth, nil)
|
||||
return collected, usage, err
|
||||
}
|
||||
|
||||
@@ -2578,8 +2577,8 @@ type geminiSSECollectStats struct {
|
||||
}
|
||||
|
||||
// collectGeminiSSEObserved 在聚合的同时把每个解包后的事件原文交给 observe(可为 nil)。
|
||||
func collectGeminiSSEObserved(body io.Reader, isOAuth bool, observe func(rawBytes []byte)) (map[string]any, *ClaudeUsage, geminiSSECollectStats, error) {
|
||||
reader := bufio.NewReader(body)
|
||||
func collectGeminiSSEObserved(cfg *config.Config, body io.Reader, isOAuth bool, observe func(rawBytes []byte)) (map[string]any, *ClaudeUsage, geminiSSECollectStats, error) {
|
||||
reader := newBoundedSSELineReader(body, cfg)
|
||||
|
||||
var last map[string]any
|
||||
var lastWithParts map[string]any
|
||||
@@ -2588,7 +2587,7 @@ func collectGeminiSSEObserved(body io.Reader, isOAuth bool, observe func(rawByte
|
||||
stats := geminiSSECollectStats{fallback: &geminiSSEFallbackBody{}}
|
||||
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
line, err := reader.ReadLineString()
|
||||
if len(line) > 0 {
|
||||
trimmed := strings.TrimRight(line, "\r\n")
|
||||
if !strings.HasPrefix(trimmed, "data:") {
|
||||
@@ -2909,7 +2908,7 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte
|
||||
return nil, errors.New("streaming not supported")
|
||||
}
|
||||
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
reader := newBoundedSSELineReader(resp.Body, s.cfg)
|
||||
usage := &ClaudeUsage{}
|
||||
observer := upstreamResponseModelObserverFromContext(c)
|
||||
if observer == nil {
|
||||
@@ -2923,7 +2922,7 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte
|
||||
finished := false
|
||||
|
||||
for {
|
||||
line, err := reader.ReadString('\n')
|
||||
line, err := reader.ReadLineString()
|
||||
// 读错误时 line 是未以换行结尾的残行,不透传也不参与用量统计;EOF 时的末行完整有效。
|
||||
if len(line) > 0 && (err == nil || errors.Is(err, io.EOF)) {
|
||||
trimmed := strings.TrimRight(line, "\r\n")
|
||||
|
||||
@@ -501,7 +501,7 @@ func TestGeminiForwardNative_CountTokensBodyLeavesNoMark(t *testing.T) {
|
||||
|
||||
func TestCollectGeminiSSEObserved_SeesTerminalChunkEvenWhenAggregateDropsIt(t *testing.T) {
|
||||
var observed []string
|
||||
collected, usage, stats, err := collectGeminiSSEObserved(strings.NewReader(geminiSignalTestProhibitedSSE), false, func(raw []byte) {
|
||||
collected, usage, stats, err := collectGeminiSSEObserved(nil, strings.NewReader(geminiSignalTestProhibitedSSE), false, func(raw []byte) {
|
||||
observed = append(observed, string(raw))
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Upstreams behind a custom base_url can stream a line that never ends. Every
|
||||
// Gemini stream reader must stop at the configured line limit instead of
|
||||
// buffering it, and must not forward a truncated prefix.
|
||||
func TestGeminiStreamsRejectOversizedUpstreamLines(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 256}}
|
||||
svc := &GeminiMessagesCompatService{cfg: cfg}
|
||||
oversized := `data: {"candidates":[{"content":{"parts":[{"text":"` + strings.Repeat("x", 4096)
|
||||
|
||||
run := map[string]func(c *gin.Context, resp *http.Response) error{
|
||||
"native": func(c *gin.Context, resp *http.Response) error {
|
||||
_, err := svc.handleNativeStreamingResponse(c, resp, time.Now(), false, &Account{ID: 1}, "")
|
||||
return err
|
||||
},
|
||||
"messages": func(c *gin.Context, resp *http.Response) error {
|
||||
_, err := svc.handleStreamingResponse(c, resp, time.Now(), "gemini-2.5-pro")
|
||||
return err
|
||||
},
|
||||
"chat_completions": func(c *gin.Context, resp *http.Response) error {
|
||||
_, err := svc.handleChatCompletionsStreamingResponseFromGemini(c, resp, time.Now(), "gemini-2.5-pro", false, false)
|
||||
return err
|
||||
},
|
||||
"collector": func(_ *gin.Context, resp *http.Response) error {
|
||||
_, _, _, err := collectGeminiSSEObserved(cfg, resp.Body, false, nil)
|
||||
return err
|
||||
},
|
||||
}
|
||||
for name, fn := range run {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:streamGenerateContent", nil)
|
||||
resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(oversized))}
|
||||
|
||||
err := fn(c, resp)
|
||||
require.Error(t, err)
|
||||
require.True(t, errors.Is(err, bufio.ErrTooLong), "got %v", err)
|
||||
require.NotContains(t, w.Body.String(), "xxxx")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
)
|
||||
@@ -179,6 +180,14 @@ func (r *boundedSSELineReader) ReadLine() ([]byte, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// ReadLineString is ReadLine for callers that keep the line as a string.
|
||||
// ReadLine returns a fresh allocation that nothing else retains, so the line is
|
||||
// handed over without a second copy.
|
||||
func (r *boundedSSELineReader) ReadLineString() (string, error) {
|
||||
line, err := r.ReadLine()
|
||||
return unsafe.String(unsafe.SliceData(line), len(line)), err
|
||||
}
|
||||
|
||||
func (s *AntigravityGatewayService) antigravitySSEConfig() *config.Config {
|
||||
if s == nil || s.settingService == nil {
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user