Files
openteam/server/internal/proxy/sqlbudget_test.go
T
Sakurasan 8c12207478 perf: 目录缓存与流式正文快路径,请求热路径开销减半
按性能分析逐项落地,实测对比(16 并发、mock 上游零延迟、SQLite):

- 每请求 SQL 10 → 2:模型/渠道目录(模型行、绑定、渠道行)进程内缓存 10s,
  运行期状态(冷却、健康)仍每次实时判定;管理端写操作经中间件、
  健康状态变化经回调立即失效。新增 TestProxyRequestSQLBudget 钉住预算。
- 端到端 p50 1.3–1.6ms → 0.66–0.70ms,RPS 3.5–8.9k → 16–18k。
- 流式正文累积:字符串 += 改 strings.Builder(原为 O(n²)),
  逐行 JSON 提取改字节快路径,并加廉价的子串预过滤、拿到输出 usage 后停累积。
  500 块:949µs/7.9MB 分配 → 83µs/136KB。
- 请求体定点改写:模型映射从整包 unmarshal/marshal 改为顶层字段替换
  (100KB:585µs → 29µs),stream_options 注入同理;requestText 改为
  只在「上游没报用量」时按需提取,亲和键改用原始体前缀。
- 渠道满载背压:新增 Acquire 有界排队(OT_PROXY_CHANNEL_ACQUIRE_WAIT,
  默认 150ms);排队仍满时返回 503 + Retry-After 而不是 502。
  实测渠道上限 4、16 并发:无排队 81 次 503;排队 150ms 后 400/400 成功。
- 记账按批聚合:同批同用户一次扣款、流水批量插入、日表按 (user,model,日期)
  聚合,替代每行 5 条语句;幂等仍靠 ref_id 唯一索引兜底。
- gorm 开启 PrepareStmt(SQL 解析此前占 CPU 15%);tiktoken 编码器按模型复用。
- 管理端用量列表不再返回原始请求/响应体(可能几十 MB),
  改为 has_raw 标记 + GET /admin/usage/:id 按需拉取,前端弹窗打开时取。

验证:go vet、go test ./...、go test -race(proxy/channel/usage/tokenizer)、
vue-tsc、eslint、vite build 全绿;本地起 mock 上游实测列表/详情接口与
管理页弹窗按需加载。
2026-10-30 14:14:21 +08:00

81 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package proxy
import (
"context"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/openteam/server/internal/channel"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
)
// sqlTracer 记录一次请求路径上打过的 SQL。
type sqlTracer struct {
gormlogger.Interface
mu sync.Mutex
list []string
}
func (s *sqlTracer) Trace(_ context.Context, _ time.Time, fc func() (string, int64), _ error) {
sql, _ := fc()
s.mu.Lock()
s.list = append(s.list, sql)
s.mu.Unlock()
}
func (s *sqlTracer) take() []string {
s.mu.Lock()
defer s.mu.Unlock()
out := s.list
s.list = nil
return out
}
// 每请求 SQL 预算:热路径上的模型/渠道目录必须走进程内缓存。
// 原本一次非流式请求要打 10 条(含同一模型查三次),缓存后只剩鉴权两条。
// 这个上限是防回归的闸门:往请求路径上新增未缓存的查询会立刻让它变红。
func TestProxyRequestSQLBudget(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"x","model":"m1","choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5}}`)
}))
defer srv.Close()
h := newHarness(t, srv.URL, 0, true, nil)
tr := &sqlTracer{Interface: gormlogger.Discard}
traced := h.db.Session(&gorm.Session{Logger: tr})
h.gw.db = traced
h.gw.ch = channel.NewService(traced, h.gw.enc)
body := `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`
// 第一次:冷缓存 + last_used_at 首次写入,不计入预算
if w := h.run(t, nil, body); w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
tr.take()
// 第二次:模型/渠道目录与系统配置都应命中缓存
if w := h.run(t, nil, body); w.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
}
sqls := tr.take()
const budget = 3 // api_keys + users(+ 偶发 last_used_at)
if len(sqls) > budget {
t.Fatalf("热路径 SQL 条数 = %d,超过预算 %d:\n%s", len(sqls), budget, joinSQL(sqls))
}
t.Logf("第二条请求 SQL = %d 条:\n%s", len(sqls), joinSQL(sqls))
}
func joinSQL(sqls []string) string {
out := ""
for i, q := range sqls {
out += " " + string(rune('1'+i)) + ". " + q + "\n"
}
return out
}