Files
traefik-llmgateway/passthrough_sse_estimate_test.go
T
lukaszraczylo a11e640230 fix(passthrough): gate and bill passthrough requests by cost budget
Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event.
2026-11-29 00:23:09 +00:00

164 lines
5.4 KiB
Go

package traefikllmgateway
import (
"bufio"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const sseTestChunk = "data: {\"id\":\"c1\",\"model\":\"gpt-5\",\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n"
func newSSEEstimateGateway(t *testing.T, upstream http.HandlerFunc) *Gateway {
t.Helper()
srv := httptest.NewServer(upstream)
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up"}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
gw, ok := h.(*Gateway)
if !ok {
t.Fatal("handler is not *Gateway")
}
gw.limiter.spawn = func(f func()) { f() }
return gw
}
func postSSE(gw *Gateway) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`))
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
return rec
}
func tokOutOf(gw *Gateway) int64 {
v, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return v
}
func TestPassthroughSSE_NoUsageChunkBillsEstimatedCompletion(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 30; i++ {
_, _ = io.WriteString(w, sseTestChunk)
}
})
if rec := postSSE(gw); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
got := tokOutOf(gw)
if got < 30 || got > 31 {
t.Errorf("tokout = %d, want 30..31 (one per data event)", got)
}
if cost, _ := gw.limiter.getCounter("user", "alice", metricCost, windowDay, time.Now()); cost <= 0 {
t.Errorf("cost = %d, want > 0", cost)
}
}
func TestPassthroughSSE_ReportedUsageWins(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 30; i++ {
_, _ = io.WriteString(w, sseTestChunk)
}
_, _ = io.WriteString(w, "data: {\"id\":\"c1\",\"choices\":[],\"usage\":{\"prompt_tokens\":42,\"completion_tokens\":9}}\n\ndata: [DONE]\n\n")
})
postSSE(gw)
if got := tokOutOf(gw); got != 9 {
t.Errorf("tokout = %d, want 9 (reported)", got)
}
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 42 {
t.Errorf("tokin = %d, want 42 (reported)", got)
}
}
func TestPassthroughSSE_HangupBeforeUsageBillsEstimate(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
for i := 0; i < 5; i++ {
_, _ = io.WriteString(w, sseTestChunk)
w.(http.Flusher).Flush()
}
<-r.Context().Done()
})
front := httptest.NewServer(gw)
defer front.Close()
req, _ := http.NewRequest(http.MethodPost, front.URL+"/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`))
req.Header.Set("Authorization", "Bearer sk-alice")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
rd := bufio.NewReader(resp.Body)
for i := 0; i < 5; i++ {
for {
line, rerr := rd.ReadString('\n')
if rerr != nil {
t.Fatalf("read: %v", rerr)
}
if line == "\n" {
break
}
}
}
_ = resp.Body.Close()
deadline := time.Now().Add(3 * time.Second)
for tokOutOf(gw) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if got := tokOutOf(gw); got < 1 || got > 6 {
t.Errorf("tokout = %d, want 1..6 after a client hang-up", got)
}
}
func TestPassthroughJSON_NoUsageStaysNoOp(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"file-1","object":"file"}`)
})
if rec := postSSE(gw); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
if got := tokOutOf(gw); got != 0 {
t.Errorf("tokout = %d, want 0", got)
}
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 0 {
t.Errorf("tokin = %d, want 0", got)
}
}
func TestSSEAccountingBuffer_CountsDataEvents(t *testing.T) {
var b sseAccountingBuffer
_, _ = b.Write([]byte(sseTestChunk + sseTestChunk))
_, _ = b.Write([]byte(": keepalive\n\n"))
_, _ = b.Write([]byte("data: [DONE]\n\n"))
if b.events != 3 {
t.Errorf("events = %d, want 3", b.events)
}
}
func TestPassthroughSSE_ReportedPromptWithoutCompletionKeptWithoutRequestBody(t *testing.T) {
gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, "data: {\"model\":\"gpt-5\",\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":0}}\n\n")
})
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", nil)
req.Header.Set("Authorization", "Bearer sk-alice")
gw.ServeHTTP(httptest.NewRecorder(), req)
if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 7 {
t.Errorf("tokin = %d, want 7 (reported prompt usage must not be dropped)", got)
}
}