Files
ModelRouter/internal/core/core_test.go
JianFeeeee 25970a2135 refactor(scheduler)!: 移除 priority 废弃字段 + 一通道一源 + discover 复用凭据
用户判据:「priority 直接移除」「即使带 key 也没有 /v1/responses」
「channel 插件的问题还没完全解决」「生图和聊天合并到一个导航项」

## 一、删除 priority(它从未参与跨源调度)

`config.Model.Priority` 号称"高者优先参与 AUTO 选源",**那是错的**:
AUTO 链由 `config.ModelScope.Tier` 驱动(scheduler.Chain),priority 只被
`bestChatModel/bestImageModel` 用于"本源内部该发哪个模型",与跨源调度无关。
把它当调度依据会让人以为拖个数字就能改顺序,改完毫无效果。

- 删 `config.Model.Priority` 字段与 `bestChatModel/bestImageModel` 的优先级比较
- 删 `seedAuto()`:**AUTO 链为空时网关应直接 503**,不能凭空播种用户没配过的档位
- 删 UI `buildLanes` 的 discovery 回退(按源 priority 自动铺开)与 sourceRows
- 清掉 config.yaml 里 140 行 priority

## 二、一通道 = 一个适配器 = 一个源(channels 插件)

旧设计「一账号一源」(`channels-<平台>-<12位hex>`) 有三个结构性后果:
1. 三个账号 ⇒ 三个源、三份同名模型,用户看到三行无法区分的东西
2. 谁先谁后**取决于注册顺序,不是余额**(rankAccounts 只用于展示,从未接进同步路径)
3. 换号要改源名 ⇒ 用户书签里的 `源:模型` 全部失效

新设计:
- 源名只跟通道绑定:`channels-<平台>`,换号 = 同名 add_source 覆盖 api_key
  (内核 AddSource 是 UpsertSourceInYAML + 内存替换),对客户端完全透明
- `pickAccountForSource()`:凭据可用 → 余额分档(先快作废后永久)→
  跳过已标记失效的号。没有 balance 声明的平台不据此排除(不因"不会查"判死)
- `request_end` 钩子:真实请求失败且是**终态**错误(需充值/封禁/凭据永久失效)
  时给当前账号打 termErr,下次选号跳过;成功则清标记。
  ⚠️ 只认终态 —— 429/超时/抖动都**不**标记(那会把好号一个个废掉)
- `refresh_creds` 每 30 分钟巡检后重新选号(兜底心跳,纯本地判定)
- 迁移:同步时自动清掉旧版按账号拆的源(按已知平台前缀匹配,不用贪婪 match)
- 顺带修:`refresh_creds` 漏认 `refresh_fn` ⇒ codearts 的 DPoP 续期永不触发

## 三、discover 支持用已存凭据(真实缺口)

刷新已有源的模型目录,此前必须让运维**再粘一次明文 key** —— 而库里是
`enc:v1:` 密文,WebUI 也不回显明文。结果就是"想刷新 → 得重新申请 key",
很多人干脆不刷,源的目录越放越旧(实例:某源 3 个生图模型从未登记)。

- `{"name":"oin"}` ⇒ 从已存源取 base_url + 解密凭据 + adapter
- 安全边界:已要求 admin;只能探测**本网关已配置的**源(不能拿任意 URL+key
  做探测,那就成了 SSRF/密钥外带);响应不回显 key

## 四、image_models 显式声明(补元数据缺失)

`discoveredModelKind` 只看上游 modality 字段,并刻意**不从模型名推断**
(错误的 kind 会毒死 AUTO 链)。但有些网关的 /v1/models 只返回
`{id,object,created,owned_by}` —— 零 modality,于是生图模型全落成 chat,
生图端点永远 `no image source configured`。

不解这个两难:默认仍完全按元数据(不猜),但允许 `image_models` **显式声明**。
写错的 id 明确报 400,不静默造一个不存在的模型。

## 五、UI:对话与生图合并为一个导航项

两者本是同一件事的两种输入(都选模型、都发请求、都读结果),只是 kind 与端点
不同。合并只发生在**导航层**:模型下拉仍按 kind 分组/禁选(把图片模型选进 chat
会请求到错误端点)。两个面板同时存在于 DOM,切换只改 display —— 来回切不会丢
已输入的文字、对话历史或已生成的图。

## 测试

- `TestUI_ImageModeIsReachableFromChatTab`:改为钉"合并后仍可达"(分段控件、
  切换函数、面板容器、端点),并断言**旧 tab 三件套必须消失**(否则 goTab 会找
  一个不存在的面板)
- 测试夹具显式建 AUTO 链(内核不再 seedAuto):默认一源一 tier 倒序
  (TestChatAUTO 验优先级);TestChatAutoChainTierFailover 自己覆盖成同 tier
  (验 tier 内轮转)—— 两者验不同机制,不能共用一个默认
- core 的一批断言从"按账号 id 找源"改为"按平台名找源"

gateway/config/provider 全绿;core 的 channels 用例全绿。
TestRealMutants 需工作树干净后才跑(其自带的变异残留防护)。

BREAKING CHANGE: config.Model.Priority 已删除。旧的 priority 字段会被 YAML
解码静默忽略(内核不校验未知字段),因此既有 config.yaml 仍可加载,但该字段
不再有任何作用 —— 调度顺序请通过 AUTO 链的 tier 表达。
2026-10-19 16:26:59 +08:00

136 lines
4.2 KiB
Go

package core
import (
"path/filepath"
"sync"
"testing"
"llmsproxy/internal/config"
)
// newTestConfig returns an in-memory config backed by temp files so
// NewFromConfig (store load, key/auto seeding, registry build) is exercised
// like production.
func newTestConfig(t *testing.T) *config.Config {
t.Helper()
dir := t.TempDir()
return &config.Config{
Path: filepath.Join(dir, "config.yaml"),
AdapterDir: filepath.Join(dir, "adapters"),
RuntimeFile: filepath.Join(dir, "runtime.json"),
Listen: "127.0.0.1:0",
DefaultModel: "AUTO",
GatewayKeys: []string{"sk-gw-test"},
Sources: []config.Source{
{Name: "s1", BaseURL: "http://127.0.0.1:1/v1", Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}}},
},
}
}
func newTestCore(t *testing.T, cfg *config.Config) *Core {
t.Helper()
c, err := NewFromConfig(cfg)
if err != nil {
t.Fatalf("core: %v", err)
}
t.Cleanup(c.Close)
return c
}
func TestCleanScopesNilForEmpty(t *testing.T) {
if got := cleanScopes(nil); got != nil {
t.Fatalf("nil in must yield nil out, got %#v", got)
}
if got := cleanScopes([]config.ModelScope{{Model: ""}}); got != nil {
t.Fatalf("all-empty entries must yield nil, got %#v", got)
}
got := cleanScopes([]config.ModelScope{{Model: "m", Source: "undefined"}})
if len(got) != 1 || got[0].Source != "" || got[0].Model != "m" {
t.Fatalf("placeholder normalization wrong: %#v", got)
}
}
// TestCreateKeyWithoutScopeUnrestricted: a user key created without a model
// scope must be unrestricted in-process (nil), identical to what config.yaml
// omitempty produces after a restart — no 403 lock-out, no silent widening.
func TestCreateKeyWithoutScopeUnrestricted(t *testing.T) {
c := newTestCore(t, newTestConfig(t))
k, err := c.CreateKey("svc", "user", nil, "")
if err != nil {
t.Fatalf("create: %v", err)
}
rec, ok := c.FindKey(k.Key)
if !ok {
t.Fatal("key not found")
}
if rec.Models != nil {
t.Fatalf("user key without scope must be unrestricted, got %#v", rec.Models)
}
}
// TestUpdateKeyPreservesScopeWhenOmitted: PUT /api/keys without a models field
// must keep the existing scope; only an explicit [] clears it.
func TestUpdateKeyPreservesScopeWhenOmitted(t *testing.T) {
c := newTestCore(t, newTestConfig(t))
k, err := c.CreateKey("svc", "user", []config.ModelScope{{Model: "gpt-4o"}}, "")
if err != nil {
t.Fatalf("create: %v", err)
}
upd, err := c.UpdateKey(k.Key, "renamed", "", nil, "")
if err != nil {
t.Fatalf("update: %v", err)
}
if len(upd.Models) != 1 || upd.Models[0].Model != "gpt-4o" {
t.Fatalf("scope must survive an update without models, got %#v", upd.Models)
}
cleared, err := c.UpdateKey(k.Key, "", "", []config.ModelScope{}, "")
if err != nil {
t.Fatalf("clear: %v", err)
}
if cleared.Models != nil {
t.Fatalf("explicit empty list must clear the scope, got %#v", cleared.Models)
}
}
// TestSaveAutoRulesNormalizesModelCase: a rule whose model name differs only
// in case must be normalized to the exact configured spelling so cooldown,
// quota windows and the upstream model id all agree.
func TestSaveAutoRulesNormalizesModelCase(t *testing.T) {
c := newTestCore(t, newTestConfig(t))
if err := c.SaveAutoRules([]config.ModelScope{{Model: "GPT-4O", Source: "s1", Tier: 1}}); err != nil {
t.Fatalf("save: %v", err)
}
ch := c.AutoChain()
if ch == nil || len(ch.Tiers) == 0 || len(ch.Tiers[0].Slots) == 0 {
t.Fatalf("chain empty: %#v", ch)
}
if got := ch.Tiers[0].Slots[0].Model; got != "gpt-4o" {
t.Fatalf("slot model must be normalized to the config spelling, got %q", got)
}
if got := ch.Tiers[0].Slots[0].Source; got != "s1" {
t.Fatalf("slot source wrong: %q", got)
}
}
// TestConcurrentKeyMutation exercises the c.cfg.Keys lock under -race: key
// creation/lookup/deletion from many goroutines at once.
func TestConcurrentKeyMutation(t *testing.T) {
c := newTestCore(t, newTestConfig(t))
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func() {
defer wg.Done()
k, err := c.CreateKey("k", "user", nil, "")
if err == nil {
if rec, ok := c.FindKey(k.Key); ok && rec.Key != k.Key {
t.Errorf("wrong key returned")
}
c.UpdateKey(k.Key, "renamed", "", nil, "")
c.DeleteKey(k.Key)
}
}()
}
wg.Wait()
}