fix: 修掉模型调用链路上的四处失效逻辑

- 超时:NewGateway 里 gw_timeout*time.Second 把已是 Duration 的值二次换算,
  int64 溢出后无论 OT_PROXY_TIMEOUT 填多少都等于没有超时,渠道 timeout_ms
  也从没被读过。现在非流式用 context deadline 约束整段时长,流式只约束首包
  (Transport.ResponseHeaderTimeout),正文不限时长,长回答不会被砍。
- 断连:上游请求改用 NewRequestWithContext 绑定客户端 context,客户端断开即
  取消上游并记 canceled,不再空转生成继续付费;PATCH 已写 200 头后不再往
  响应里追加错误体。
- 白名单:APIKey.AllowedModels 以前只存不用,现在 Auth 注入 context 并参与
  判定(用户黑名单 > 密钥白名单 > 用户白名单 > 全局)。
- 选路:模型已有渠道绑定时只用绑定渠道,都不可用直接 503 no_channel,不再
  把请求发给不认识它的渠道;新增运行期健康(连续 3 次网络错误/超时/429/5xx
  进 30s 冷却,成功清零),与 60s 一次的 /models 探测互补。
- 密钥 API:PATCH 回显更新后的完整对象;限额填 0 统一视为不限制(原来
  token 配额存 0 会让密钥第一次请求就被 429 打死,而请求配额存 0 又等于
  不限制,两个字段语义相反);前端编辑框总是提交白名单,清空能真的取消。

测试:新增 proxy 链路集成测试(超时生效、流式不被截断、断连取消并记账、
密钥白名单 403、连续 429 后候选剔除)与 channel 用例(绑定模型不退全局、
冷却阈值与到期恢复、成功清零)。
This commit is contained in:
Sakurasan committed 2026-10-16 19:15:51 +08:00
1 parent d911881499
commit e865f69a41
10 files changed
+659 -69

No files matched your search

+88 -9
View File
@@ -5,8 +5,10 @@ package channel
import (
"crypto/rand"
"errors"
"log"
"math/big"
"sync"
"time"
"github.com/openteam/server/internal/pkg/crypto"
"github.com/openteam/server/internal/store"
@@ -21,10 +23,29 @@ type Service struct {
mu sync.Mutex
sems map[uint64]chan struct{}
runt map[uint64]*runtimeHealth
// 运行期冷却参数;NewService 给默认值,测试可覆盖。
failThreshold int
cooldownFor time.Duration
}
// runtimeHealth 运行期健康:连续可重试失败(网络错误/超时/429/5xx)累计到阈值进入冷却。
// 与 HealthMonitor 的探测结果相互独立——探测只看 /models 是否 200,
// 覆盖不了"models 正常但对话接口一直报错"的渠道。
type runtimeHealth struct {
fails int
until time.Time
}
func NewService(db *gorm.DB, enc *crypto.Encryptor) *Service {
return &Service{db: db, enc: enc, sems: map[uint64]chan struct{}{}}
return &Service{
db: db, enc: enc,
sems: map[uint64]chan struct{}{},
runt: map[uint64]*runtimeHealth{},
failThreshold: 3,
cooldownFor: 30 * time.Second,
}
}
// Candidate 一个候选渠道 + 该模型的映射关系。
@@ -33,18 +54,20 @@ type Candidate struct {
UpstreamModel string // 全局模型在此渠道的映射名(无绑定则为空,用客户端模型名)
}
// Candidates 返回可用渠道候选:健康 + 启用,按优先级、权重降序、id 升序排列。
// model 非空时优先取绑定该模型的渠道(携带 upstream_model 映射);无绑定则退回全局。
// Candidates 返回可用渠道候选:健康 + 启用 + 不在运行期冷却,按优先级、权重降序、id 升序排列。
// model 非空且该模型有渠道绑定时,只返回绑定渠道(携带 upstream_model 映射);
// 绑定渠道全部不可用则返回空(上层报 no_channel),不会退化到不认识该模型的全局渠道。
// 仅当模型完全没有任何绑定时才退回全局渠道。
func (s *Service) Candidates(model string) []Candidate {
if model != "" {
var b []store.ChannelModelBinding
var modelIDs []uint64
var b []store.ChannelModelBinding
s.db.Model(&store.Model{}).Where("name = ? AND enabled = ?", model, true).Pluck("id", &modelIDs)
if len(modelIDs) > 0 {
s.db.Where("model_id IN ?", modelIDs).Find(&b)
if cands := s.loadBound(b); len(cands) > 0 {
return cands
}
}
if len(b) > 0 {
return s.loadBound(b)
}
}
var chs []store.Channel
@@ -52,12 +75,15 @@ func (s *Service) Candidates(model string) []Candidate {
Order("priority ASC, weight DESC, id ASC").Find(&chs)
out := make([]Candidate, 0, len(chs))
for i := range chs {
if s.InCooldown(chs[i].ID) {
continue
}
out = append(out, Candidate{Channel: &chs[i]})
}
return out
}
// loadBound 按绑定顺序加载渠道候选,过滤健康/启用,携带 upstream_model 映射。
// loadBound 按绑定顺序加载渠道候选,过滤健康/启用/运行期冷却,携带 upstream_model 映射。
func (s *Service) loadBound(bindings []store.ChannelModelBinding) []Candidate {
if len(bindings) == 0 {
return nil
@@ -80,7 +106,7 @@ func (s *Service) loadBound(bindings []store.ChannelModelBinding) []Candidate {
}
out := make([]Candidate, 0, len(ids))
for _, id := range ids {
if ch, ok := byID[id]; ok {
if ch, ok := byID[id]; ok && !s.InCooldown(id) {
out = append(out, Candidate{Channel: ch, UpstreamModel: byChannel[id].UpstreamModel})
}
}
@@ -154,3 +180,56 @@ func (s *Service) TryAcquire(ch *store.Channel) (func(), bool) {
func (s *Service) UpstreamKey(ch *store.Channel) (string, error) {
return s.enc.Decrypt(ch.APIKeyEnc)
}
// ---------------------------------------------------------------------------
// 运行期健康(进程内,与 /v1/models 探测独立)
// ReportFailure 记一次可重试的上游失败;连续达 failThreshold 次则该渠道进入冷却,
// 期间不出现在候选集里。冷却到期后需再攒满阈值才会被剔除。
func (s *Service) ReportFailure(ch *store.Channel) {
s.mu.Lock()
st := s.runt[ch.ID]
if st == nil {
st = &runtimeHealth{}
s.runt[ch.ID] = st
}
st.fails++
tripped := false
if st.fails >= s.failThreshold {
st.fails = 0
st.until = time.Now().Add(s.cooldownFor)
tripped = true
}
s.mu.Unlock()
if tripped {
log.Printf("channel: %q entered runtime cooldown (%s)", ch.Name, s.cooldownFor)
}
}
// ReportSuccess 上游正常返回响应头,清空该渠道的连续失败计数。
func (s *Service) ReportSuccess(ch *store.Channel) {
s.mu.Lock()
if st, ok := s.runt[ch.ID]; ok {
st.fails = 0
}
s.mu.Unlock()
}
// InCooldown 渠道是否处于运行期冷却;过期则清掉状态、恢复可用。
// until 为零值表示只在累计失败、尚未触发冷却,此时不能清状态(否则计数永远攒不满阈值)。
func (s *Service) InCooldown(id uint64) bool {
s.mu.Lock()
defer s.mu.Unlock()
st, ok := s.runt[id]
if !ok {
return false
}
if st.until.IsZero() {
return false
}
if time.Now().Before(st.until) {
return true
}
delete(s.runt, id)
return false
}
+76
View File
@@ -129,3 +129,79 @@ func TestHealthStartStops(t *testing.T) {
m.Start(ctx)
cancel() // 不应 panic
}
// 模型被渠道绑定后只允许走绑定渠道;绑定渠道不可用时返回空候选(上层 503),
// 不能退化到"不认识这个模型"的全局渠道。
func TestBoundModelDoesNotFallBackToGlobal(t *testing.T) {
db := newTestDB(t)
bound := seedChannel(t, db, "bound", 1, 0, 4)
seedChannel(t, db, "other", 1, 1, 4)
m := store.Model{Name: "gpt-m", Enabled: true}
if err := db.Create(&m).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&store.ChannelModelBinding{ChannelID: bound, ModelID: m.ID, UpstreamModel: "gpt-m"}).Error; err != nil {
t.Fatal(err)
}
s := NewService(db, crypto.NewEncryptor("test-master-key-1234567890"))
cands := s.Candidates("gpt-m")
if len(cands) != 1 || cands[0].Channel.Name != "bound" {
t.Fatalf("绑定模型应只命中 bound,实际 %+v", cands)
}
if cands[0].UpstreamModel != "gpt-m" {
t.Fatalf("映射名丢失:%s", cands[0].UpstreamModel)
}
db.Model(&store.Channel{}).Where("id = ?", bound).Update("enabled", false)
if got := s.Candidates("gpt-m"); len(got) != 0 {
t.Fatalf("绑定渠道停用后应为空候选,实际 %d", len(got))
}
// 完全未绑定的模型仍然走全局
if got := s.Candidates("unmanaged"); len(got) != 1 || got[0].Channel.Name != "other" {
t.Fatalf("未纳管模型应退回全局渠道,实际 %+v", got)
}
}
// 运行期冷却:连续失败才踢,成功即清零,冷却到期自动恢复。
func TestRuntimeCooldownThresholdAndExpiry(t *testing.T) {
db := newTestDB(t)
id := seedChannel(t, db, "r", 1, 0, 4)
var ch store.Channel
db.First(&ch, id)
s := NewService(db, crypto.NewEncryptor("test-master-key-1234567890"))
s.cooldownFor = 60 * time.Millisecond
// 默认阈值 3:前两次失败不该踢,第三次才进冷却
s.ReportFailure(&ch)
s.ReportFailure(&ch)
if s.InCooldown(id) {
t.Fatal("未达阈值(3 次连续)不应进冷却")
}
s.ReportFailure(&ch)
if !s.InCooldown(id) {
t.Fatal("连续达阈值应进冷却")
}
if got := s.Candidates(""); len(got) != 0 {
t.Fatalf("冷却渠道不应进候选,实际 %d", len(got))
}
if got := s.Candidates("whatever"); len(got) != 0 {
t.Fatalf("全局候选也应过滤冷却渠道,实际 %d", len(got))
}
time.Sleep(80 * time.Millisecond)
if s.InCooldown(id) {
t.Fatal("冷却到期应恢复可用")
}
if got := s.Candidates(""); len(got) != 1 {
t.Fatalf("恢复后应重新进候选,实际 %d", len(got))
}
s.ReportFailure(&ch)
s.ReportSuccess(&ch)
s.ReportFailure(&ch)
if s.InCooldown(id) {
t.Fatal("非连续失败不应触发冷却")
}
}