diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index dcac458..18713ef 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -30,6 +30,11 @@ jobs: cache: true - name: Vet run: go vet ./... + - name: Test + run: go test ./... + - name: Race test + if: matrix.os == 'ubuntu-latest' + run: go test -race ./... - name: Build run: go build -trimpath ./cmd/opencode2api diff --git a/.gitignore b/.gitignore index fe2e912..e0f69c8 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,9 @@ node_modules/ coverage.out *.test *.test.exe + +*.rotation.json +.rotation-*.tmp + +# Local credentials, deployment backups, and verification artifacts +.local/ diff --git a/.prettierignore b/.prettierignore index e816de9..b4d91f5 100644 --- a/.prettierignore +++ b/.prettierignore @@ -9,3 +9,6 @@ config.json.bak *.models.catalog.json coverage.out package-lock.json + +.local/ +*.rotation.json diff --git a/README.md b/README.md index e539f5b..0bc7a46 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ The executable includes the WebUI. Running the service requires no Node.js runti - Dynamic model discovery, native protocol metadata, and disk caches. - A separate management port with configuration editing, a Playground, diagnostics, token statistics, and live logs. - Configuration hot reload with validation before switching new requests to a replacement gateway. +- Go subscription quota dashboard with remaining percentages, reset times, and available models. +- Local API key creation, naming, enabling, disabling, and deletion with immediate updates. +- Sticky `sota` / `sweet` model groups with ordering, failure fallback, streaming protection, and persisted state. + +See the [management console guide (Chinese)](docs/management.zh-CN.md) for the new pages and configuration. ## Quick start diff --git a/README.zh-CN.md b/README.zh-CN.md index 3974944..85a7177 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -16,6 +16,11 @@ WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 - 动态模型发现、原生协议与能力信息、磁盘缓存。 - 独立管理端口,支持配置编辑、Playground、路由诊断、Token 统计和实时日志。 - 配置热重载:先验证新配置,再切换新请求使用的 Gateway。 +- Go 共享套餐额度看板,显示剩余百分比、重置时间和可用模型。 +- API Key 生成、自定义、命名、启停和删除,变更立即生效。 +- `sota` / `sweet` 分组别名,支持模型排序、故障切换、流式输出保护和状态恢复。 + +新增页面及调用示例见[管理控制台说明](docs/management.zh-CN.md)。 ## 快速开始 diff --git a/config.example.json b/config.example.json index 9c52e21..b17f423 100644 --- a/config.example.json +++ b/config.example.json @@ -43,5 +43,16 @@ "reasoning": { "effort": "high", "effort_by_model": {} + }, + "rotation": { + "sota": { + "alias": "sota", + "order": ["deepseek-v4.1-flash", "glm-5.3", "grok-4.6", "kimi-k3", "qwen3.8-max"] + }, + "sweet": { + "alias": "sweet", + "order": [] + }, + "first_output_seconds": 30 } } diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md new file mode 100644 index 0000000..a4c5ff5 --- /dev/null +++ b/docs/management.zh-CN.md @@ -0,0 +1,90 @@ +# 管理控制台:模型轮转、Go 额度与 API Key + +本文说明三个新增管理页面的使用方式、配置和错误处理。 + +## 模型与额度 + +管理页面 `/#model-quotas`,登录后读取 `GET /api/model-quotas`。 + +- 模型来自网关同步的 OpenCode Go 目录,支持搜索和复制模型 ID。 +- 额度由网关使用已配置的 Go Key 查询 `https://opencode.ai/zen/go/v1/usage`。浏览器不会收到上游 Key。 +- 显示 5 小时、每周、每月窗口的剩余百分比和重置时间。接口只提供共享套餐窗口,不提供独立的逐模型余额,不推算金额或可用次数。多个 Key 的额度不相加。 +- 成功响应缓存 60 秒,失败缓存 15 秒;失败时保留上次成功结果并明确标记历史数据。没有成功数据时显示未知。 +- 页面打开期间每 60 秒查询一次;离开页面或隐藏浏览器时停止周期查询。手动刷新也受服务端缓存约束。 + +依据:[OpenCode 官方额度接口源码](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts)。该接口未列入正式 API 文档,若响应格式变化,会显示查询异常而非虚构额度。 + +## API Key 管理 + +管理页面 `/#api-keys`,支持列表、生成、自定义、重命名、启用、停用、删除和创建后复制环境变量。 + +- 管理的是网关的 `server_keys`,不修改 OpenCode Go 的上游 Key。 +- 自动生成 192 位随机密钥;自定义密钥为 16–256 位英文字母、数字、`-`、`_` 或 `.`。 +- 列表只显示名称、尾码、状态和创建时间。创建后可复制完整密钥及环境变量。 +- 变更热应用;停用和删除后,新请求返回 401。在途请求可以完成。至少保留一个启用的 Key。 +- 所有管理接口需要登录,写操作需要 CSRF Token。 +- 元数据以 `server_key_metadata` 保存在原配置中,按 Key 指纹关联;已有 `server_keys` 自动兼容。 +- 当前未实现按 Key 单独分配模型权限、用量配额或过期时间。 + +## 验证和构建 + +```bash +go test ./... +go test -race ./... +go vet ./... +npm run check:web +npx prettier --check webui/index.html webui/app.js webui/styles.css +go build -trimpath -o opencode2api ./cmd/opencode2api +``` + +升级前请备份程序、配置及轮转状态,再停止服务并替换可执行文件。旧版本不认识新增的 `server_key_metadata` 和 `rotation` 字段;回退时应同时恢复旧程序和旧配置。 + +## SOTA / 甜点模型轮转 + +管理页:`/#rotation`。调用时继续使用 网关的 Base URL(默认 +`http://127.0.0.1:8080/v1`)和已有 API Key,将 `model` 设为 `sota` 或 +`sweet`。两个别名列入 `/v1/models`,支持 Chat Completions、Responses 和 +Messages,以及这三种协议的流式输出。真实模型 ID 的原有调用路径保持不变。 + +- SOTA 固定成员:`deepseek-v4.1-flash`、`glm-5.3`、`grok-4.6`、`kimi-k3`、 + `qwen3.8-max`,默认按上述顺序。 +- 甜点组包含其余 Go 可用模型,初次以 `glm-5.3-flash` 为首,随后按名称排序。 + 新模型追加在末尾;下架或协议不受支持的模型保留在列表,但不参与调用。 +- 每组共享一个当前模型。成功后保持位置;失败切换后,下次从新位置开始。 + 并发请求通过位置版本号避免旧请求把游标移回去;手动切换不打断在途回答。 +- 普通错误每模型最多 3 次(包含首次),每请求最多消耗 3 个普通错误模型预算。 + 模型耗尽重试后暂停 15 秒。分组请求不使用原有 Key 重试、跨 Tier 降级、 + 自动重定向或 stale-reasoning 补发,也不因单个模型故障暂停整个 Go Key。 +- 429 或明确额度错误直接跳到下一模型,不新增普通错误模型计数;已经发生的 + 普通错误仍计数。允许遍历整组,同一请求不重复模型。暂停时间采用 Retry-After, + 未提供时为 60 秒。共享套餐额度只用于展示,不能保证换模型后就有余额。 +- 整体超时沿用 `retry.timeout_seconds`。`rotation.first_output_seconds` 默认 + 30 秒,限制每次等待首个有效输出的时间,不限制已经开始的正常流式回答。 +- 流式 start/role/usage 前导事件会等到有效输出或正常结束后再提交。提交前错误 + 可重试;提交后中断会保留已输出内容、追加协议对应的 SSE 错误并结束,随后 + 推进当前位置,下一次请求使用下一个模型。不会在同一响应里拼接替代答案。 + 调用方取消不会触发暂停或切换。 +- 响应 JSON / SSE 的 `model` 保持请求别名,`X-Resolved-Model` 标记实际模型。 + 用量按实际上游模型记录。轮转日志与管理页面仅保留分类后的错误原因, + 不记录上游错误正文、请求正文或密钥。最近保留 100 条尝试和每组 30 条切换。 + +配置保存于 `config.json` 的 `rotation` 字段:`sota` / `sweet` 各有 `alias` +和 `order`;状态单独原子写入 `config.json.rotation.json`(0600),包括当前 +位置、版本、动态追加的顺序、暂停期限和最近记录。修改 Key 或其他配置时 +沿用同一个轮转状态管理器。页面展示状态写入失败提示,首次无法写入则拒绝启动。 + +管理接口均需要现有管理 Session,写入另需 CSRF: + +- `GET /api/rotation`:分组配置、可用状态、暂停期限、切换和尝试记录。 +- `PUT /api/rotation`:提交 `sota` / `sweet` 的 `alias`、完整 `order`,以及 + `first_output_seconds`;别名不得重复或与真实模型 ID 冲突,成员不得跨组。 +- `POST /api/rotation/current`:`{"group":"sota","model":"glm-5.3"}`;立即 + 修改当前模型并解除该模型的临时暂停。 + +验证:`go test -race ./...`、`go vet ./...`、`npm run check:web`。 +模拟上游测试覆盖 9 次普通错误上限、超过 3 个额度跳过、混合错误预算、 +Retry-After、单个模型故障不影响 Key、三种入口协议的跨协议转换、成功保持、 +别名发现与用量归属、畸形响应、输出前错误、首个输出超时、输出后故障、 +调用方取消、在途回答不受手动切换影响、并发版本保护、下架和重启恢复。 +上线前建议使用独立配置及端口验证管理登录、CSRF、页面排序与保存、别名冲突、 +Key 配置热更新和真实 Go 请求。测试与正式配置、凭证、日志及运行状态不应提交到仓库。 diff --git a/internal/admin/api_keys.go b/internal/admin/api_keys.go new file mode 100644 index 0000000..a5c3d4d --- /dev/null +++ b/internal/admin/api_keys.go @@ -0,0 +1,174 @@ +package admin + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" +) + +type APIKeyView struct { + ID string `json:"id"` + Name string `json:"name"` + Display string `json:"display"` + Enabled bool `json:"enabled"` + CreatedAt *time.Time `json:"created_at,omitempty"` +} + +func apiKeyViews(cfg config.Config) []APIKeyView { + items := make([]APIKeyView, 0, len(cfg.ServerKeys)) + for i, key := range cfg.ServerKeys { + id := config.Fingerprint(key) + meta := cfg.ServerKeyMetadata[id] + name := meta.Name + if name == "" { + name = fmt.Sprintf("已有 Key %d", i+1) + } + item := APIKeyView{ID: id, Name: name, Display: config.MaskValue(key), Enabled: !meta.Disabled} + if !meta.CreatedAt.IsZero() { + created := meta.CreatedAt + item.CreatedAt = &created + } + items = append(items, item) + } + return items +} + +func (a *Server) handleListAPIKeys(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Cache-Control", "no-store") + httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": apiKeyViews(a.manager.Config())}) +} + +func validateKeyName(name string) error { + if name == "" || len([]rune(name)) > 80 { + return errors.New("名称需为 1–80 个字符") + } + return nil +} + +func addAPIKey(cfg *config.Config, name, key string) error { + if err := validateKeyName(name); err != nil { + return err + } + if len(key) < 16 || len(key) > 256 { + return errors.New("自定义 Key 需为 16–256 位") + } + for _, ch := range key { + if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.') { + return errors.New("Key 仅支持英文字母、数字、短横线、下划线和点") + } + } + if len(cfg.ServerKeys) >= 200 { + return errors.New("最多创建 200 个 API Key") + } + id := config.Fingerprint(key) + for _, existing := range cfg.ServerKeys { + if config.Fingerprint(existing) == id { + return errors.New("此 API Key 已存在") + } + } + if cfg.ServerKeyMetadata == nil { + cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{} + } + cfg.ServerKeys = append(cfg.ServerKeys, key) + cfg.ServerKeyMetadata[id] = config.ServerKeyMetadata{Name: name, CreatedAt: time.Now().UTC()} + return nil +} + +func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) { + var input struct { + Name string `json:"name"` + Value string `json:"value"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, 400, "invalid_request", err.Error()) + return + } + key := input.Value + if key == "" { + var random [24]byte + if _, err := rand.Read(random[:]); err != nil { + writeAdminError(w, 500, "generation_failed", "无法生成密钥") + return + } + key = "sk-local-" + hex.EncodeToString(random[:]) + } + _, err := a.manager.Update(func(cfg *config.Config) error { return addAPIKey(cfg, strings.TrimSpace(input.Name), key) }) + if err != nil { + writeAdminError(w, 400, "key_create_failed", a.manager.Redact(err.Error())) + return + } + w.Header().Set("Cache-Control", "no-store") + httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": apiKeyViews(a.manager.Config())}) +} + +func changeAPIKey(cfg *config.Config, id string, name *string, enabled *bool, remove bool) error { + index := -1 + for i, key := range cfg.ServerKeys { + if config.Fingerprint(key) == id { + index = i + break + } + } + if index < 0 { + return errors.New("API Key 不存在,请刷新列表") + } + if cfg.ServerKeyMetadata == nil { + cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{} + } + if remove { + cfg.ServerKeys = append(cfg.ServerKeys[:index], cfg.ServerKeys[index+1:]...) + delete(cfg.ServerKeyMetadata, id) + } else { + meta := cfg.ServerKeyMetadata[id] + if name != nil { + value := strings.TrimSpace(*name) + if err := validateKeyName(value); err != nil { + return err + } + meta.Name = value + } + if enabled != nil { + meta.Disabled = !*enabled + } + cfg.ServerKeyMetadata[id] = meta + } + if cfg.FirstEnabledServerKey() == "" { + return errors.New("至少保留一个启用的 API Key,请先创建替代密钥") + } + return nil +} + +func (a *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) { + var input struct { + Name *string `json:"name"` + Enabled *bool `json:"enabled"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, 400, "invalid_request", err.Error()) + return + } + _, err := a.manager.Update(func(cfg *config.Config) error { + return changeAPIKey(cfg, r.PathValue("id"), input.Name, input.Enabled, false) + }) + if err != nil { + writeAdminError(w, 400, "key_update_failed", a.manager.Redact(err.Error())) + return + } + a.handleListAPIKeys(w, r) +} + +func (a *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) { + _, err := a.manager.Update(func(cfg *config.Config) error { return changeAPIKey(cfg, r.PathValue("id"), nil, nil, true) }) + if err != nil { + writeAdminError(w, 400, "key_delete_failed", a.manager.Redact(err.Error())) + return + } + a.handleListAPIKeys(w, r) +} diff --git a/internal/admin/api_keys_test.go b/internal/admin/api_keys_test.go new file mode 100644 index 0000000..0a9bbee --- /dev/null +++ b/internal/admin/api_keys_test.go @@ -0,0 +1,65 @@ +package admin + +import ( + "encoding/json" + "strings" + "testing" + + "opencode2api/internal/config" +) + +func TestManagedKeyLifecycle(t *testing.T) { + base := "sk-existing-1234567890" + cfg := config.Config{ServerKeys: []string{base}} + key := "sk-client-12345678901234" + if err := addAPIKey(&cfg, "笔记助手", key); err != nil { + t.Fatal(err) + } + if err := addAPIKey(&cfg, "重复", key); err == nil { + t.Fatal("duplicate accepted") + } + views, _ := json.Marshal(apiKeyViews(cfg)) + if strings.Contains(string(views), key) || strings.Contains(string(views), base) { + t.Fatal("list leaked secret") + } + id := config.Fingerprint(key) + enabled := false + candidate := config.Clone(cfg) + if err := changeAPIKey(&candidate, id, nil, &enabled, false); err != nil { + t.Fatal(err) + } + if candidate.ServerKeyEnabled(key) || !cfg.ServerKeyEnabled(key) { + t.Fatal("clone metadata aliases source") + } + cfg = candidate + name := "新的名称" + if err := changeAPIKey(&cfg, id, &name, nil, false); err != nil { + t.Fatal(err) + } + if cfg.ServerKeyMetadata[id].Name != name { + t.Fatal("rename not applied") + } + if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, &enabled, false); err == nil { + t.Fatal("last active key disabled") + } + // Failed mutations are applied only to a clone by RuntimeManager.Update. + cfg = config.Config{ServerKeys: []string{base, key}} + if err := changeAPIKey(&cfg, id, nil, nil, true); err != nil { + t.Fatal(err) + } + if len(cfg.ServerKeys) != 1 || cfg.ServerKeys[0] != base { + t.Fatal("wrong key deleted") + } + if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, nil, true); err == nil { + t.Fatal("last key deleted") + } +} + +func TestCustomKeyValidation(t *testing.T) { + for _, key := range []string{"short", "long-key with-space-123", "含中文的密钥12345678901234567890", "secret\n12345678901234567890"} { + cfg := config.Config{} + if addAPIKey(&cfg, "test", key) == nil { + t.Errorf("invalid key accepted") + } + } +} diff --git a/internal/admin/debug.go b/internal/admin/debug.go index 3435dbe..62a1cc5 100644 --- a/internal/admin/debug.go +++ b/internal/admin/debug.go @@ -115,11 +115,11 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) { return } cfg := a.manager.Config() - if len(cfg.ServerKeys) == 0 { + if cfg.FirstEnabledServerKey() == "" { writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured") return } - request.Header.Set("Authorization", "Bearer "+cfg.ServerKeys[0]) + request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey()) if selectedKey != nil { request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID})) } diff --git a/internal/admin/model_quotas.go b/internal/admin/model_quotas.go new file mode 100644 index 0000000..d1842ed --- /dev/null +++ b/internal/admin/model_quotas.go @@ -0,0 +1,171 @@ +package admin + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" +) + +type quotaWindow struct { + Status string `json:"status"` + UsedPercent float64 `json:"used_percent"` + RemainingPercent float64 `json:"remaining_percent"` + ResetsAt time.Time `json:"resets_at"` +} + +type quotaAccount struct { + ID string `json:"id"` + Display string `json:"display"` + Status string `json:"status"` + Error string `json:"error,omitempty"` + FetchedAt *time.Time `json:"fetched_at,omitempty"` + CheckedAt time.Time `json:"checked_at"` + Windows map[string]quotaWindow `json:"windows,omitempty"` +} + +type quotaCacheEntry struct { + Account quotaAccount + Expires time.Time +} + +// The first-party endpoint returns subscription-wide percentages, not balances +// for individual models. Never infer model dollars or sum keys' shared quotas. +// Reference: anomalyco/opencode packages/console/app/src/routes/zen/go/v1/usage.ts +func decodeQuota(reader io.Reader) (map[string]quotaWindow, error) { + var body struct { + Usage map[string]struct { + Status string `json:"status"` + Percent *float64 `json:"percent"` + ResetsAt time.Time `json:"resetsAt"` + } `json:"usage"` + } + if err := json.NewDecoder(io.LimitReader(reader, 1<<20)).Decode(&body); err != nil { + return nil, errors.New("OpenCode 返回的额度格式无法识别") + } + result := map[string]quotaWindow{} + for _, name := range []string{"rolling", "weekly", "monthly"} { + item, ok := body.Usage[name] + if !ok || item.Percent == nil || *item.Percent < 0 || *item.Percent > 100 || item.ResetsAt.IsZero() || (item.Status != "ok" && item.Status != "rate-limited") { + return nil, errors.New("OpenCode 返回的额度窗口不完整") + } + result[name] = quotaWindow{Status: item.Status, UsedPercent: *item.Percent, RemainingPercent: 100 - *item.Percent, ResetsAt: item.ResetsAt} + } + return result, nil +} + +func fetchQuota(ctx context.Context, endpoint, key string) (map[string]quotaWindow, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, errors.New("额度查询地址无效") + } + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("User-Agent", "opencode2api-admin/1.0") + req.Header.Set("Accept", "application/json") + req.Header.Set("x-opencode-session", "opencode2api-quota-"+config.Fingerprint(key)) + client := &http.Client{Timeout: 12 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} + resp, err := client.Do(req) + if err != nil { + return nil, errors.New("暂时无法连接 OpenCode,请稍后刷新") + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + switch resp.StatusCode { + case 401: + return nil, errors.New("Go API Key 无效或已被撤销") + case 403: + return nil, errors.New("此 Key 未获准读取 Go 套餐额度") + case 429: + return nil, errors.New("额度查询过于频繁,请稍后刷新") + default: + return nil, fmt.Errorf("OpenCode 额度接口返回 HTTP %d", resp.StatusCode) + } + } + return decodeQuota(resp.Body) +} + +func refreshQuota(ctx context.Context, endpoint, key string, previous quotaCacheEntry) quotaCacheEntry { + now := time.Now().UTC() + account := previous.Account + account.ID, account.Display = config.Fingerprint(key), config.MaskValue(key) + account.CheckedAt = now + windows, err := fetchQuota(ctx, endpoint, key) + if err != nil { + account.Status, account.Error = "unavailable", err.Error() + if account.FetchedAt != nil { + account.Status = "stale" + } + return quotaCacheEntry{Account: account, Expires: now.Add(15 * time.Second)} + } + account.Status, account.Error, account.Windows = "ok", "", windows + account.FetchedAt = &now + return quotaCacheEntry{Account: account, Expires: now.Add(60 * time.Second)} +} + +func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + cfg := a.manager.Config() + endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage" + accounts := make([]quotaAccount, len(cfg.GoKeys)) + // Coalesce refreshes from multiple browser tabs; at most four upstream + // queries run at a time. The cache is pruned when upstream credentials change. + a.quotaMu.Lock() + if a.quotaCache == nil { + a.quotaCache = map[string]quotaCacheEntry{} + } + entries := make([]quotaCacheEntry, len(cfg.GoKeys)) + var wg sync.WaitGroup + sem := make(chan struct{}, 4) + for i, key := range cfg.GoKeys { + cacheID := endpoint + "|" + config.Fingerprint(key) + previous := a.quotaCache[cacheID] + if time.Now().Before(previous.Expires) { + entries[i] = previous + continue + } + wg.Add(1) + go func(i int, key string, previous quotaCacheEntry) { + defer wg.Done() + select { + case sem <- struct{}{}: + defer func() { <-sem }() + case <-r.Context().Done(): + return + } + entries[i] = refreshQuota(r.Context(), endpoint, key, previous) + }(i, key, previous) + } + wg.Wait() + newCache := map[string]quotaCacheEntry{} + for i, key := range cfg.GoKeys { + newCache[endpoint+"|"+config.Fingerprint(key)] = entries[i] + accounts[i] = entries[i].Account + } + a.quotaCache = newCache + a.quotaMu.Unlock() + all, _ := a.manager.DebugModels() + type modelView struct { + ID string `json:"id"` + Protocol string `json:"protocol"` + } + models := []modelView{} + for _, model := range all { + if model.AvailableGo && model.RouteError == "" { + protocol := model.NativeProtocols[config.TierGo] + models = append(models, modelView{ID: model.Model, Protocol: string(protocol)}) + } + } + httpx.WriteJSON(w, 200, map[string]any{ + "models": models, "accounts": accounts, "scope": "shared_subscription", "source": endpoint, + "cache_seconds": 60, "catalog": a.manager.Resources().Models, + "note": "OpenCode 返回套餐共享额度,未提供逐模型独立余额;多个 Go Key 可能属于同一套餐,不能相加。百分比由上游取整。", + }) +} diff --git a/internal/admin/model_quotas_test.go b/internal/admin/model_quotas_test.go new file mode 100644 index 0000000..fd38825 --- /dev/null +++ b/internal/admin/model_quotas_test.go @@ -0,0 +1,74 @@ +package admin + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const validQuota = `{"usage":{"rolling":{"status":"ok","percent":19,"resetsAt":"2026-09-20T12:00:00Z"},"weekly":{"status":"rate-limited","percent":100,"resetsAt":"2026-09-21T00:00:00Z"},"monthly":{"status":"ok","percent":0,"resetsAt":"2026-10-20T00:00:00Z"}}}` + +func TestQuotaDecode(t *testing.T) { + windows, err := decodeQuota(strings.NewReader(validQuota)) + if err != nil { + t.Fatal(err) + } + if windows["rolling"].RemainingPercent != 81 || windows["weekly"].RemainingPercent != 0 || windows["monthly"].RemainingPercent != 100 { + t.Fatal("incorrect percentage semantics") + } + for _, raw := range []string{`{}`, strings.Replace(validQuota, `"percent":19`, `"percent":null`, 1), strings.Replace(validQuota, `"percent":19`, `"percent":101`, 1), strings.Replace(validQuota, "2026-09-20T12:00:00Z", "invalid", 1), strings.Replace(validQuota, `"status":"ok"`, `"status":"unknown"`, 1)} { + if _, err := decodeQuota(strings.NewReader(raw)); err == nil { + t.Fatal("malformed quota accepted") + } + } +} + +func TestQuotaFailureRetainsLastGoodAndRedacts(t *testing.T) { + failing := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer test-upstream-secret" { + t.Error("missing authorization") + } + if r.Header.Get("User-Agent") != "opencode2api-admin/1.0" { + t.Error("incorrect identity") + } + if failing { + w.WriteHeader(401) + w.Write([]byte(`{"error":"test-upstream-secret"}`)) + return + } + w.Write([]byte(validQuota)) + })) + defer srv.Close() + first := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{}) + if first.Account.Status != "ok" { + t.Fatal(first.Account.Error) + } + failing = true + stale := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", first) + if stale.Account.Status != "stale" || stale.Account.Windows["rolling"].RemainingPercent != 81 || !stale.Account.FetchedAt.Equal(*first.Account.FetchedAt) { + t.Fatal("last known quota lost") + } + encoded, _ := json.Marshal(stale.Account) + if strings.Contains(string(encoded), "test-upstream-secret") { + t.Fatal("secret leaked") + } + missing := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{}) + if missing.Account.Status != "unavailable" || missing.Account.Windows != nil { + t.Fatal("invented unavailable balance") + } +} + +func TestQuotaDoesNotFollowRedirect(t *testing.T) { + reached := false + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true })) + defer target.Close() + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, 302) })) + defer source.Close() + if _, err := fetchQuota(context.Background(), source.URL, "secret"); err == nil || reached { + t.Fatal("redirect leaked credentials") + } +} diff --git a/internal/admin/rotation.go b/internal/admin/rotation.go new file mode 100644 index 0000000..5cba909 --- /dev/null +++ b/internal/admin/rotation.go @@ -0,0 +1,63 @@ +package admin + +import ( + "fmt" + "net/http" + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "slices" +) + +func (a *Server) handleRotation(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + httpx.WriteJSON(w, 200, a.manager.RotationSnapshot()) +} +func (a *Server) handleSaveRotation(w http.ResponseWriter, r *http.Request) { + var input config.RotationConfig + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, 400, "invalid_request", err.Error()) + return + } + _, err := a.manager.Update(func(cfg *config.Config) error { + if err := input.Validate(nil); err != nil { + return err + } + state := a.manager.RotationSnapshot() + for i, g := range state.Groups { + order := input.SOTA.Order + if i == 1 { + order = input.Sweet.Order + } + if len(order) != len(g.Order) { + return fmt.Errorf("模型列表已更新,请刷新后重新排序") + } + for _, v := range order { + if !slices.Contains(g.Order, v) { + return fmt.Errorf("只能调整组内模型的顺序") + } + } + } + cfg.Rotation = input + return nil + }) + if err != nil { + writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error())) + return + } + a.handleRotation(w, r) +} +func (a *Server) handleSelectRotation(w http.ResponseWriter, r *http.Request) { + var input struct { + Group string `json:"group"` + Model string `json:"model"` + } + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, 400, "invalid_request", err.Error()) + return + } + if err := a.manager.SelectRotation(input.Group, input.Model); err != nil { + writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error())) + return + } + a.handleRotation(w, r) +} diff --git a/internal/admin/server.go b/internal/admin/server.go index 6cb14bf..de59e3d 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -32,6 +32,8 @@ type Server struct { attempts map[string]loginWindow debugAttempts map[string]loginWindow lastInference *DebugInferenceResult + quotaMu sync.Mutex + quotaCache map[string]quotaCacheEntry } func New(manager *gateway.RuntimeManager, monitor *telemetry.Monitor, logs *telemetry.LogHub, logger *slog.Logger) *Server { @@ -53,6 +55,14 @@ func (a *Server) Handler() http.Handler { mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount)))) mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor))) mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels))) + mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation))) + mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation)))) + mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation)))) + mux.Handle("GET /api/model-quotas", a.authenticate(http.HandlerFunc(a.handleModelQuotas))) + mux.Handle("GET /api/api-keys", a.authenticate(http.HandlerFunc(a.handleListAPIKeys))) + mux.Handle("POST /api/api-keys", a.authenticate(a.csrf(http.HandlerFunc(a.handleCreateAPIKey)))) + mux.Handle("PATCH /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleUpdateAPIKey)))) + mux.Handle("DELETE /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleDeleteAPIKey)))) mux.Handle("POST /api/debug/inference", a.authenticate(a.csrf(http.HandlerFunc(a.handleDebugInference)))) mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs))) mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream))) @@ -189,7 +199,9 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { reasoning = *update.Reasoning } candidate := config.Config{ - Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile, + ServerKeyMetadata: current.ServerKeyMetadata, + Rotation: current.Rotation, + Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile, Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, diff --git a/internal/config/config.go b/internal/config/config.go index e028442..d1d8446 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -16,24 +16,23 @@ import ( ) type Config struct { - Listen string `json:"listen"` - ServerKeys []string `json:"server_keys"` - ZenKeys []string `json:"zen_keys"` - GoKeys []string `json:"go_keys"` - Anonymous bool `json:"anonymous"` - Proxies []string `json:"proxies"` - ProxyFile string `json:"proxyfile"` - Upstream UpstreamConfig `json:"upstream"` - Retry RetryConfig `json:"retry"` - Models ModelsConfig `json:"models"` - Performance PerformanceConfig `json:"performance"` - Logging LoggingConfig `json:"logging"` - WebUI WebUIConfig `json:"webui"` - Prefer Tier `json:"prefer"` - // Reasoning configures a forced thinking level. Both fields are optional - // and empty by default, so an existing configuration keeps the client's own - // level untouched. - Reasoning ReasoningConfig `json:"reasoning"` + Rotation RotationConfig `json:"rotation"` + Listen string `json:"listen"` + ServerKeys []string `json:"server_keys"` + ServerKeyMetadata map[string]ServerKeyMetadata `json:"server_key_metadata,omitempty"` + ZenKeys []string `json:"zen_keys"` + GoKeys []string `json:"go_keys"` + Anonymous bool `json:"anonymous"` + Proxies []string `json:"proxies"` + ProxyFile string `json:"proxyfile"` + Upstream UpstreamConfig `json:"upstream"` + Retry RetryConfig `json:"retry"` + Models ModelsConfig `json:"models"` + Performance PerformanceConfig `json:"performance"` + Logging LoggingConfig `json:"logging"` + WebUI WebUIConfig `json:"webui"` + Prefer Tier `json:"prefer"` + Reasoning ReasoningConfig `json:"reasoning"` effectiveProxies []string } @@ -150,6 +149,10 @@ func Load(path string) (Config, error) { // Normalize resolves external inputs and validates a Config supplied by // either the JSON file or the authenticated management API. func Normalize(path string, cfg Config) (Config, error) { + cfg.Rotation.Defaults() + if err := cfg.Rotation.Validate(nil); err != nil { + return Config{}, err + } trimList(&cfg.ServerKeys) trimList(&cfg.ZenKeys) trimList(&cfg.GoKeys) @@ -174,6 +177,9 @@ func Normalize(path string, cfg Config) (Config, error) { if len(cfg.ServerKeys) == 0 { return Config{}, errors.New("server_keys must contain at least one local key") } + if cfg.FirstEnabledServerKey() == "" { + return Config{}, errors.New("至少保留一个启用的 API Key") + } if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 { return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key unless anonymous is enabled") } @@ -317,7 +323,14 @@ func (cfg *Config) PasswordForSave() { } func Clone(cfg Config) Config { + cfg.Rotation.SOTA.Order = append([]string(nil), cfg.Rotation.SOTA.Order...) + cfg.Rotation.Sweet.Order = append([]string(nil), cfg.Rotation.Sweet.Order...) cfg.ServerKeys = append([]string(nil), cfg.ServerKeys...) + metadata := make(map[string]ServerKeyMetadata, len(cfg.ServerKeyMetadata)) + for id, item := range cfg.ServerKeyMetadata { + metadata[id] = item + } + cfg.ServerKeyMetadata = metadata cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...) cfg.GoKeys = append([]string(nil), cfg.GoKeys...) cfg.Proxies = append([]string(nil), cfg.Proxies...) diff --git a/internal/config/rotation.go b/internal/config/rotation.go new file mode 100644 index 0000000..2eef2b1 --- /dev/null +++ b/internal/config/rotation.go @@ -0,0 +1,63 @@ +package config + +import ( + "fmt" + "regexp" + "slices" +) + +var SOTAModels = []string{"deepseek-v4.1-flash", "glm-5.3", "grok-4.6", "kimi-k3", "qwen3.8-max"} + +type RotationGroup struct { + Alias string `json:"alias"` + Order []string `json:"order"` +} +type RotationConfig struct { + SOTA RotationGroup `json:"sota"` + Sweet RotationGroup `json:"sweet"` + FirstOutputSeconds int `json:"first_output_seconds"` +} + +func IsSOTA(model string) bool { return slices.Contains(SOTAModels, model) } +func (c *RotationConfig) Defaults() { + if c.SOTA.Alias == "" { + c.SOTA.Alias = "sota" + } + if c.Sweet.Alias == "" { + c.Sweet.Alias = "sweet" + } + if len(c.SOTA.Order) == 0 { + c.SOTA.Order = slices.Clone(SOTAModels) + } + if c.FirstOutputSeconds == 0 { + c.FirstOutputSeconds = 30 + } +} +func (c RotationConfig) Validate(realModels []string) error { + if c.FirstOutputSeconds < 1 || c.FirstOutputSeconds > 300 { + return fmt.Errorf("首个有效输出超时需为 1–300 秒") + } + if c.SOTA.Alias == c.Sweet.Alias { + return fmt.Errorf("两个分组的别名不能相同") + } + valid := regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) + for i, g := range []RotationGroup{c.SOTA, c.Sweet} { + if !valid.MatchString(g.Alias) { + return fmt.Errorf("别名需为 1–64 位英文字母、数字、点、短横线或下划线") + } + if slices.Contains(realModels, g.Alias) || IsSOTA(g.Alias) || slices.Contains(c.Sweet.Order, g.Alias) { + return fmt.Errorf("别名不能与真实模型 ID 相同") + } + seen := map[string]bool{} + for _, model := range g.Order { + if model == "" || seen[model] || IsSOTA(model) != (i == 0) { + return fmt.Errorf("模型顺序包含重复、空值或不属于该分组的模型") + } + seen[model] = true + } + if i == 0 && len(g.Order) != len(SOTAModels) { + return fmt.Errorf("SOTA 组必须包含指定的五个模型") + } + } + return nil +} diff --git a/internal/config/rotation_test.go b/internal/config/rotation_test.go new file mode 100644 index 0000000..b0d754f --- /dev/null +++ b/internal/config/rotation_test.go @@ -0,0 +1,32 @@ +package config + +import "testing" + +func TestRotationConfigValidationAndClone(t *testing.T) { + c := RotationConfig{} + c.Defaults() + if err := c.Validate(nil); err != nil { + t.Fatal(err) + } + for _, change := range []func(*RotationConfig){ + func(c *RotationConfig) { c.SOTA.Alias = c.Sweet.Alias }, + func(c *RotationConfig) { c.SOTA.Alias = "glm-5.3" }, + func(c *RotationConfig) { c.SOTA.Alias = "real-model" }, + func(c *RotationConfig) { c.Sweet.Alias = "bad alias" }, + func(c *RotationConfig) { c.SOTA.Order = []string{"other-model"} }, + func(c *RotationConfig) { c.Sweet.Order = []string{"glm-5.3"} }, + func(c *RotationConfig) { c.Sweet.Order = []string{"x", "x"} }, + func(c *RotationConfig) { c.FirstOutputSeconds = -1 }, + } { + candidate := Clone(Config{Rotation: c}).Rotation + change(&candidate) + if candidate.Validate([]string{"real-model"}) == nil { + t.Fatal("accepted invalid config", candidate) + } + } + clone := Clone(Config{Rotation: c}) + clone.Rotation.SOTA.Order[0] = "changed" + if c.SOTA.Order[0] != "deepseek-v4.1-flash" { + t.Fatal("cloning aliased config") + } +} diff --git a/internal/config/server_keys.go b/internal/config/server_keys.go new file mode 100644 index 0000000..1dcb3cf --- /dev/null +++ b/internal/config/server_keys.go @@ -0,0 +1,24 @@ +package config + +import "time" + +// Metadata is keyed by the existing key fingerprint; secret values remain in +// server_keys for compatibility with existing configuration and clients. +type ServerKeyMetadata struct { + Name string `json:"name"` + Disabled bool `json:"disabled,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` +} + +func (c Config) ServerKeyEnabled(key string) bool { + return !c.ServerKeyMetadata[Fingerprint(key)].Disabled +} + +func (c Config) FirstEnabledServerKey() string { + for _, key := range c.ServerKeys { + if c.ServerKeyEnabled(key) { + return key + } + } + return "" +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 67c58c8..7493088 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -19,6 +19,7 @@ import ( "opencode2api/internal/jsonutil" "opencode2api/internal/models" wire "opencode2api/internal/protocol" + "opencode2api/internal/rotation" "opencode2api/internal/telemetry" ) @@ -27,6 +28,7 @@ const maxRequestBody = 32 << 20 const anonymousZenKey = "public" type Gateway struct { + rotation *rotation.Manager cfg config.Config logger *slog.Logger transports *transportPool @@ -38,6 +40,11 @@ type Gateway struct { } func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) { + cfg.Rotation.Defaults() + rotationManager, err := rotation.New("", cfg.Rotation) + if err != nil { + return nil, err + } transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) if err != nil { return nil, err @@ -55,6 +62,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*G catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) return &Gateway{ cfg: cfg, + rotation: rotationManager, logger: logger, transports: transports, zenNodes: zenNodes, @@ -84,6 +92,9 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { } valid := false for _, key := range g.cfg.ServerKeys { + if !g.cfg.ServerKeyEnabled(key) { + continue + } for _, candidate := range candidates { if len(candidate) == len(key) && subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1 { valid = true @@ -123,6 +134,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model") return } + if id := g.rotation.GroupID(model); id != "" { + g.handleRotation(w, r, external, payload, id, model) + return + } if !g.catalog.Supported(model) { wire.WriteError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") return diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 929f2d8..eac5236 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -153,5 +153,8 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { } data = append(data, entry) } + for _, group := range g.rotation.Snapshot().Groups { + data = append(data, map[string]any{"id": group.Alias, "object": "model", "created": now, "owned_by": "opencode-go-rotation"}) + } httpx.WriteJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data}) } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index b3d843a..deb6f28 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -155,6 +155,7 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { } if zen != nil || goModels != nil { g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) + g.syncRotation() if ctx.Err() == nil { if err := g.catalog.SaveCache(); err != nil { g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err) diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go new file mode 100644 index 0000000..b25abd8 --- /dev/null +++ b/internal/gateway/rotation.go @@ -0,0 +1,359 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/identity" + "opencode2api/internal/jsonutil" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/rotation" + "opencode2api/internal/telemetry" +) + +func (g *Gateway) syncRotation() { + available := map[string]bool{} + for _, model := range g.catalog.List() { + if _, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil { + available[model] = true + } + } + g.rotation.Sync(available) +} +func (m *RuntimeManager) RotationSnapshot() rotation.Snapshot { + r := m.current.Load() + r.gateway.syncRotation() + return m.rotation.Snapshot() +} +func (m *RuntimeManager) SelectRotation(id, model string) error { + m.updateMu.Lock() + defer m.updateMu.Unlock() + m.current.Load().gateway.syncRotation() + return m.rotation.Manual(id, model) +} + +// Explicit quota markers only: ordinary provider errors must keep their budget. +func quotaError(status int, body string) bool { + if status == 429 { + return true + } + body = strings.ToLower(body) + for _, marker := range []string{"insufficient_quota", "quota_exceeded", "quota exceeded", "quota exhausted", "rate_limit", "rate limit", "rate-limit", "usage_limit", "usage limit", "insufficient balance", "credit balance is too low", "额度不足", "配额已用尽"} { + if strings.Contains(body, marker) { + return true + } + } + return false +} + +type groupAttempt struct { + err error + quota, committed bool + pause time.Duration + reason string +} + +func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, external wire.Protocol, payload map[string]any, id, alias string) { + g.syncRotation() + ctx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) + defer cancel() + ids := identity.DeriveRequestIDs(r, payload) + meta := telemetry.MetaFromRequest(r) + if meta != nil { + meta.Request = ids.Request + meta.ModelAlias = alias + } + visited := map[string]bool{} + ordinaryModels, total := 0, 0 + for ctx.Err() == nil { + token, ok := g.rotation.Select(id, visited) + if !ok { + break + } + visited[token.Model] = true + route, err := g.catalog.RouteForTier(token.Model, config.TierGo, false, g.goNodes.Len() > 0) + if err != nil { + continue + } + counted := false + for n := 1; n <= 3 && ctx.Err() == nil; n++ { + total++ + if meta != nil { + meta.Model = token.Model + meta.Tier = "go" + meta.Protocol = route.Protocol + meta.Attempts = total + meta.Usage = wire.Usage{} + meta.UsageReported = false + } + result := g.rotationAttempt(ctx, w, r, external, payload, alias, route, ids, total) + outcome := result.reason + if result.err == nil { + outcome = "success" + } + var clientWrite *wire.ClientWriteError + canceled := r.Context().Err() != nil || errors.As(result.err, &clientWrite) + if canceled { + outcome = "client_canceled" + if meta != nil { + meta.Outcome = outcome + } + } + g.rotation.Record(rotation.Attempt{Request: ids.Request, Alias: alias, Model: token.Model, Number: total, Outcome: outcome}) + if state := g.rotation.Snapshot(); state.PersistenceError != "" { + g.logger.Error("rotation state persistence failed", "component", "rotation", "event", "rotation_persistence_failed") + } + g.logger.Info("model rotation attempt", "component", "rotation", "event", "rotation_attempt", "request_id", ids.Request, "alias", alias, "model", token.Model, "attempt", total, "reason", outcome) + if canceled { + return + } + if result.err == nil { + return + } + if result.committed { + if meta != nil { + meta.Outcome = "stream_error" + } + pause := 15 * time.Second + if result.quota { + pause = result.pause + } + g.rotation.Fail(token, pause, result.reason) + return + } + if ctx.Err() != nil { + g.rotation.Fail(token, 15*time.Second, "request_timeout") + break + } + if result.quota { + g.rotation.Fail(token, result.pause, result.reason) + break + } + if !counted { + ordinaryModels++ + counted = true + } + if n == 3 { + g.rotation.Fail(token, 15*time.Second, result.reason) + } + } + if ordinaryModels >= 3 { + break + } + } + if r.Context().Err() != nil { + return + } + status := http.StatusServiceUnavailable + message := "该分组暂无可用模型(已暂停、下架、额度不足或重试次数已用尽),请稍后重试" + if ctx.Err() != nil { + status = http.StatusGatewayTimeout + message = "分组请求整体超时" + } + wire.WriteError(w, external, status, message, "rotation_unavailable", ids.Request) +} + +func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, original *http.Request, external wire.Protocol, payload map[string]any, alias string, route models.Route, ids identity.RequestIDs, attempt int) groupAttempt { + result := groupAttempt{reason: "upstream_error", pause: 60 * time.Second} + ctx, cancel := context.WithCancel(parent) + defer cancel() + seconds := g.rotation.Snapshot().FirstOutputSeconds + timer := time.AfterFunc(time.Duration(seconds)*time.Second, cancel) + defer timer.Stop() + copyPayload := make(map[string]any, len(payload)) + for k, v := range payload { + copyPayload[k] = v + } + copyPayload["model"] = route.ID + bodies, err := g.prepareRouteBodies(external, route, copyPayload) + if err != nil { + result.err = err + result.reason = "request_conversion_error" + return result + } + body, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo) + cursor := g.goNodes.CursorFor(ids.Session) + var node *upstreamNode + // Each group attempt is exactly one HTTP call. Key selection may change, + // but there is no nested retry, stale-reasoning replay, or model-wide key ban. + for n := 0; n < attempt; n++ { + node = cursor.Next() + } + if node == nil { + result.err = errors.New("no Go key") + return result + } + proxy := g.goNodes.Proxy(node) + if proxy == nil { + result.err = errors.New("no proxy") + return result + } + req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) + if err != nil { + result.err = err + return result + } + // A reused connection must not cause net/http to implicitly replay POSTs. + req.GetBody = nil + client := *proxy.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy) + started := time.Now() + resp, err := client.Do(req) + g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started)) + if resp != nil { + defer resp.Body.Close() + } + if err != nil { + result.err = err + result.reason = "transport_error" + if ctx.Err() != nil { + result.reason = "first_output_timeout" + } + return result + } + retryAfter := resp.Header.Get("Retry-After") + if pause := parseRetryAfter(retryAfter); pause > 0 { + result.pause = pause + } else if strings.TrimSpace(retryAfter) == "0" { + result.pause = 0 + } else if _, err := http.ParseTime(retryAfter); err == nil { + result.pause = 0 + } + if resp.StatusCode/100 != 2 { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + result.err = fmt.Errorf("upstream HTTP %d", resp.StatusCode) + result.quota = quotaError(resp.StatusCode, string(b)) + result.reason = fmt.Sprintf("http_%d", resp.StatusCode) + if result.quota { + result.reason = "quota_or_rate_limit" + } + return result + } + stream := jsonutil.BoolAt(payload, "stream") + ready := func() error { + if !timer.Stop() || ctx.Err() != nil { + return context.DeadlineExceeded + } + w.Header().Set("X-Resolved-Model", route.ID) + w.Header().Set("x-request-id", ids.Request) + w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("X-Accel-Buffering", "no") + return nil + } + meta := telemetry.MetaFromContext(parent) + if stream { + if meta != nil { + meta.Stream = true + } + if g.monitor != nil { + g.monitor.BeginStream() + defer g.monitor.EndStream() + } + usage, reported, committed, err := wire.RotationStream(original.Context(), w, resp.Body, route.Protocol, external, alias, ready) + if meta != nil { + meta.Usage = usage + meta.UsageReported = reported + } + result.err = err + result.committed = committed + result.reason = "stream_error" + var failure *wire.StreamFailure + if errors.As(err, &failure) { + result.quota = quotaError(0, failure.Type+" "+failure.Message) + } + if result.quota { + result.reason = "quota_or_rate_limit" + } else if !committed && ctx.Err() != nil { + result.reason = "first_output_timeout" + } + return result + } + b, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) + if err == nil && len(b) > 64<<20 { + err = errors.New("response exceeds size limit") + } + if err != nil { + result.err = err + result.reason = "response_read_error" + return result + } + if !timer.Stop() || ctx.Err() != nil { + result.err = context.DeadlineExceeded + result.reason = "first_output_timeout" + return result + } + if shaped { + b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID) + } + var document map[string]any + if err == nil { + err = json.Unmarshal(b, &document) + } + if err == nil && document == nil { + err = errors.New("empty upstream response") + } + if err == nil && document["error"] != nil { + result.quota = quotaError(0, string(b)) + err = errors.New("upstream error envelope") + } + if err == nil { + valid := false + switch route.Protocol { + case wire.Chat: + _, valid = document["choices"].([]any) + case wire.Anthropic: + _, valid = document["content"].([]any) + case wire.Responses: + _, valid = document["output"].([]any) + } + if !valid { + err = errors.New("invalid response schema") + } + } + if err == nil && external != route.Protocol { + b, err = wire.ConvertResponse(route.Protocol, external, b) + } + if err != nil { + result.err = err + result.reason = "response_conversion_error" + if result.quota { + result.reason = "quota_or_rate_limit" + } + return result + } + if meta != nil { + meta.Usage, meta.UsageReported = wire.ResponseUsage(external, b) + } + document = nil + if err = json.Unmarshal(b, &document); err != nil { + result.err = err + result.reason = "response_conversion_error" + return result + } + document["model"] = alias + b, err = json.Marshal(document) + if err != nil { + result.err = err + return result + } + w.Header().Set("X-Resolved-Model", route.ID) + w.Header().Set("x-request-id", ids.Request) + w.Header().Set("Content-Type", "application/json") + _, err = w.Write(b) + if err != nil { + result.err = &wire.ClientWriteError{Err: err} + } + result.committed = true + return result +} diff --git a/internal/gateway/rotation_test.go b/internal/gateway/rotation_test.go new file mode 100644 index 0000000..a318abe --- /dev/null +++ b/internal/gateway/rotation_test.go @@ -0,0 +1,373 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "opencode2api/internal/config" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" +) + +func rotationGateway(t *testing.T, models []string, fn http.HandlerFunc) *Gateway { + t.Helper() + up := httptest.NewServer(fn) + t.Cleanup(up.Close) + cfg := config.Config{ServerKeys: []string{"local"}, GoKeys: []string{"go-key-one", "go-key-two"}, Prefer: config.TierGo, Upstream: config.UpstreamConfig{Go: up.URL}, Retry: config.RetryConfig{MaxAttempts: 99, TimeoutSeconds: 15}, Models: config.ModelsConfig{RefreshSeconds: 300}, Performance: config.PerformanceConfig{ConnectTimeoutSeconds: 1}} + g, err := New(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), nil) + if err != nil { + t.Fatal(err) + } + native := map[string]wire.Protocol{} + for _, model := range models { + native[model] = wire.Chat + } + g.catalog.ReplaceWithCapabilities(nil, models, map[config.Tier]map[string]wire.Protocol{config.TierGo: native}, nil, nil) + t.Cleanup(func() { + for _, p := range g.transports.items { + p.client.CloseIdleConnections() + } + }) + return g +} +func modelBody(r *http.Request) map[string]any { + var p map[string]any + _ = json.NewDecoder(r.Body).Decode(&p) + return p +} +func replyChat(w http.ResponseWriter, model string, stream bool) { + if stream { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, "data: {\"id\":\"answer\",\"model\":%q,\"choices\":[{\"delta\":{\"content\":\"complete answer\"}}]}\n\ndata: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":2,\"completion_tokens\":3}}\n\ndata: [DONE]\n\n", model) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":"answer","object":"chat.completion","model":%q,"choices":[{"index":0,"message":{"role":"assistant","content":"complete answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}`, model) +} +func callRotation(g *Gateway, model string, stream bool) (*httptest.ResponseRecorder, *telemetry.RequestMeta) { + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(fmt.Sprintf(`{"model":%q,"stream":%t,"messages":[{"role":"user","content":"hi"}]}`, model, stream))) + r.Header.Set("Authorization", "Bearer local") + meta := &telemetry.RequestMeta{} + r = r.WithContext(telemetry.WithRequestMeta(r.Context(), meta)) + w := httptest.NewRecorder() + g.Handler().ServeHTTP(w, r) + return w, meta +} +func TestRotationBudgets(t *testing.T) { + for _, tc := range []struct { + name string + status func(string, int) int + want int + code int + }{ + {"ordinary three models times three", func(string, int) int { return 500 }, 9, 503}, + {"quota skips more than three", func(m string, _ int) int { + if m == "f" { + return 200 + } + return 429 + }, 6, 200}, + {"whole group quota", func(string, int) int { return 429 }, 6, 503}, + {"mixed quota keeps ordinary budget", func(_ string, n int) int { + if n == 2 { + return 429 + } + return 500 + }, 8, 503}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := []string{} + per := map[string]int{} + g := rotationGateway(t, []string{"a", "b", "c", "d", "e", "f"}, func(w http.ResponseWriter, r *http.Request) { + p := modelBody(r) + m := p["model"].(string) + calls = append(calls, m) + per[m]++ + status := tc.status(m, len(calls)) + if status == 200 { + replyChat(w, m, false) + return + } + w.Header().Set("Retry-After", "120") + w.WriteHeader(status) + fmt.Fprint(w, `{"error":{"message":"failed"}}`) + }) + w, _ := callRotation(g, "sweet", false) + if len(calls) != tc.want || w.Code != tc.code { + t.Fatalf("calls=%v status=%d body=%s", calls, w.Code, w.Body) + } + for _, node := range g.goNodes.nodes { + if node.cooldownUntil.Load() != 0 { + t.Fatal("model failure cooled entire key") + } + } + if tc.name == "whole group quota" { + for _, until := range g.rotation.Snapshot().Groups[1].Paused { + if time.Until(until) < 119*time.Second { + t.Fatal("Retry-After ignored") + } + } + } + }) + } +} +func TestRotationSuccessAliasesAndDirectModels(t *testing.T) { + calls := []string{} + g := rotationGateway(t, []string{"glm-5.3-flash", "deepseek-v4.1-flash", "glm-5.3"}, func(w http.ResponseWriter, r *http.Request) { + p := modelBody(r) + m := p["model"].(string) + calls = append(calls, m) + replyChat(w, m, p["stream"] == true) + }) + for _, alias := range []string{"sota", "sweet"} { + for _, stream := range []bool{false, true, false} { + w, meta := callRotation(g, alias, stream) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"model":"`+alias+`"`) || w.Header().Get("X-Resolved-Model") == "" { + t.Fatalf("%s: %s", alias, w.Body) + } + if meta.Model == alias || meta.ModelAlias != alias || !meta.UsageReported || meta.Usage.Output != 3 { + t.Fatalf("incorrect real-model usage: %+v", meta) + } + } + } + if !slices.Equal(calls, []string{"deepseek-v4.1-flash", "deepseek-v4.1-flash", "deepseek-v4.1-flash", "glm-5.3-flash", "glm-5.3-flash", "glm-5.3-flash"}) { + t.Fatal(calls) + } + w, _ := callRotation(g, "glm-5.3", false) + if !strings.Contains(w.Body.String(), `"model":"glm-5.3"`) || w.Header().Get("X-Resolved-Model") != "" { + t.Fatal("direct route changed") + } + r := httptest.NewRequest("GET", "/v1/models", nil) + r.Header.Set("Authorization", "Bearer local") + w = httptest.NewRecorder() + g.Handler().ServeHTTP(w, r) + for _, alias := range []string{"sota", "sweet"} { + if !strings.Contains(w.Body.String(), `"id":"`+alias+`"`) { + t.Fatal("alias missing") + } + } +} +func TestRotationStreamingBoundaries(t *testing.T) { + for _, tc := range []struct { + name, first string + wantFirst int + partial bool + }{ + {"error before content", "data: {\"error\":{\"type\":\"rate_limit_error\",\"message\":\"rate limit\"}}\n\n", 2, false}, + {"invalid prelude", "data: invalid\n\n", 4, false}, + {"partial then error", "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"partial original\"}}]}\n\ndata: {\"error\":{\"message\":\"provider failed\"}}\n\n", 1, true}, + {"partial then eof", "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"partial original\"}}]}\n\n", 1, true}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := []string{} + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + p := modelBody(r) + m := p["model"].(string) + calls = append(calls, m) + w.Header().Set("Content-Type", "text/event-stream") + if m == "a" { + fmt.Fprint(w, tc.first) + return + } + replyChat(w, m, true) + }) + w, _ := callRotation(g, "sweet", true) + if len(calls) != tc.wantFirst { + t.Fatal(calls) + } + if tc.partial { + if strings.Contains(w.Body.String(), "complete answer") || !strings.Contains(w.Body.String(), "partial original") || !strings.Contains(w.Body.String(), "upstream_error") { + t.Fatal(w.Body) + } + if g.rotation.Snapshot().Groups[1].Current != "b" { + t.Fatal("next request was not advanced") + } + w, _ = callRotation(g, "sweet", true) + if calls[len(calls)-1] != "b" || !strings.Contains(w.Body.String(), "complete answer") { + t.Fatal(calls, w.Body) + } + } else if !strings.Contains(w.Body.String(), "complete answer") || strings.Contains(w.Body.String(), "upstream_error") { + t.Fatal(w.Body) + } + }) + } +} +func TestRotationMalformedResponseAndCrossProtocol(t *testing.T) { + for _, endpoint := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"} { + t.Run(endpoint, func(t *testing.T) { + calls := 0 + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + p := modelBody(r) + calls++ + if p["model"] == "a" { + fmt.Fprint(w, `{"unexpected":"schema"}`) + return + } + if r.URL.Path != "/v1/messages" { + t.Errorf("protocol not reconverted: %s", r.URL.Path) + } + fmt.Fprint(w, `{"id":"x","type":"message","role":"assistant","model":"b","content":[{"type":"text","text":"anthropic answer"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":3}}`) + }) + g.catalog.ReplaceWithCapabilities(nil, []string{"a", "b"}, map[config.Tier]map[string]wire.Protocol{config.TierGo: {"a": wire.Chat, "b": wire.Anthropic}}, nil, nil) + input := `{"model":"sweet","messages":[{"role":"user","content":"hello"}],"max_tokens":50}` + if endpoint == "/v1/responses" { + input = `{"model":"sweet","input":"hello"}` + } + r := httptest.NewRequest("POST", endpoint, strings.NewReader(input)) + r.Header.Set("Authorization", "Bearer local") + w := httptest.NewRecorder() + g.Handler().ServeHTTP(w, r) + if calls != 4 || w.Code != 200 || !strings.Contains(w.Body.String(), "anthropic answer") || !strings.Contains(w.Body.String(), `"model":"sweet"`) { + t.Fatal(calls, w.Code, w.Body) + } + }) + } +} +func TestRotationFirstOutputTimeoutAndCancellation(t *testing.T) { + t.Run("timeout before content", func(t *testing.T) { + var mu sync.Mutex + calls := []string{} + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + m := modelBody(r)["model"].(string) + mu.Lock() + calls = append(calls, m) + mu.Unlock() + if m == "a" { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"id\":\"x\",\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + replyChat(w, m, true) + }) + cfg := g.cfg.Rotation + cfg.FirstOutputSeconds = 1 + g.rotation.Configure(cfg) + w, _ := callRotation(g, "sweet", true) + if w.Code != 200 || w.Header().Get("X-Resolved-Model") != "b" { + t.Fatal(w.Code, w.Body) + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(calls, []string{"a", "a", "a", "b"}) { + t.Fatal(calls) + } + }) + t.Run("caller cancellation", func(t *testing.T) { + entered := make(chan struct{}) + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + close(entered) + <-r.Context().Done() + }) + ctx, cancel := context.WithCancel(context.Background()) + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sweet","messages":[],"stream":true}`)).WithContext(ctx) + r.Header.Set("Authorization", "Bearer local") + done := make(chan struct{}) + go func() { g.Handler().ServeHTTP(httptest.NewRecorder(), r); close(done) }() + <-entered + cancel() + <-done + state := g.rotation.Snapshot().Groups[1] + if state.Current != "a" || len(state.Paused) != 0 { + t.Fatal("cancel rotated", state) + } + }) +} + +func TestRotationStreamingCrossProtocol(t *testing.T) { + for _, endpoint := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"} { + t.Run(endpoint, func(t *testing.T) { + calls := 0 + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + p := modelBody(r) + calls++ + if p["model"] == "a" { + w.WriteHeader(429) + return + } + if r.URL.Path != "/v1/messages" { + t.Errorf("wrong protocol %s", r.URL.Path) + } + fmt.Fprint(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"x\",\"model\":\"b\",\"usage\":{\"input_tokens\":2}}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"full answer\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":3}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") + }) + g.catalog.ReplaceWithCapabilities(nil, []string{"a", "b"}, map[config.Tier]map[string]wire.Protocol{config.TierGo: {"a": wire.Chat, "b": wire.Anthropic}}, nil, nil) + input := `{"model":"sweet","stream":true,"messages":[{"role":"user","content":"hello"}],"max_tokens":50}` + if endpoint == "/v1/responses" { + input = `{"model":"sweet","stream":true,"input":"hello"}` + } + r := httptest.NewRequest("POST", endpoint, strings.NewReader(input)) + r.Header.Set("Authorization", "Bearer local") + w := httptest.NewRecorder() + g.Handler().ServeHTTP(w, r) + if calls != 2 || w.Code != 200 || !strings.Contains(w.Body.String(), "full answer") || !strings.Contains(w.Body.String(), `"model":"sweet"`) || strings.Contains(w.Body.String(), "upstream_error") { + t.Fatal(calls, w.Code, w.Body) + } + }) + } +} + +type signalWriter struct { + *httptest.ResponseRecorder + once sync.Once + first chan struct{} +} + +func (w *signalWriter) Write(b []byte) (int, error) { + n, e := w.ResponseRecorder.Write(b) + w.once.Do(func() { close(w.first) }) + return n, e +} +func TestRotationInflightPinnedAndCancelAfterOutput(t *testing.T) { + for _, cancelClient := range []bool{false, true} { + t.Run(fmt.Sprint(cancelClient), func(t *testing.T) { + resume := make(chan struct{}) + g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) { + modelBody(r) + fmt.Fprint(w, "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n") + w.(http.Flusher).Flush() + select { + case <-resume: + fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\" last\"}}]}\n\ndata: [DONE]\n\n") + case <-r.Context().Done(): + } + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sweet","stream":true,"messages":[]}`)).WithContext(ctx) + r.Header.Set("Authorization", "Bearer local") + w := &signalWriter{ResponseRecorder: httptest.NewRecorder(), first: make(chan struct{})} + done := make(chan struct{}) + go func() { g.Handler().ServeHTTP(w, r); close(done) }() + <-w.first + if cancelClient { + cancel() + } else { + if e := g.rotation.Manual("sweet", "b"); e != nil { + t.Fatal(e) + } + close(resume) + } + <-done + s := g.rotation.Snapshot().Groups[1] + if cancelClient { + if s.Current != "a" || len(s.Paused) > 0 { + t.Fatal("cancel after output rotated") + } + } else if s.Current != "b" || !strings.Contains(w.Body.String(), " last") || w.Header().Get("X-Resolved-Model") != "a" { + t.Fatal("inflight stream interrupted or cursor reverted", s, w.Body) + } + }) + } +} diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 2b97c50..3a976f7 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -13,6 +13,7 @@ import ( "opencode2api/internal/config" modelcatalog "opencode2api/internal/models" "opencode2api/internal/protocol" + "opencode2api/internal/rotation" "opencode2api/internal/telemetry" ) @@ -30,6 +31,7 @@ type ApplyResult struct { } type RuntimeManager struct { + rotation *rotation.Manager configPath string root context.Context logger *slog.Logger @@ -84,6 +86,12 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi // bootstrap password and must not be retained. _ = os.Remove(configPath + ".bak") } + cfg.Rotation.Defaults() + rotationManager, err := rotation.New(configPath+".rotation.json", cfg.Rotation) + if err != nil { + return nil, err + } + manager.rotation = rotationManager runtime, err := manager.build(cfg) if err != nil { return nil, err @@ -93,6 +101,10 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelcatalog.CatalogCachePath(configPath), "error", err) } } + if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil { + return nil, err + } + runtime.gateway.syncRotation() manager.current.Store(runtime) manager.redactor.Replace(cfg) telemetry.SetLogLevel(manager.level, cfg.Logging.Level) @@ -106,6 +118,7 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) { if err != nil { return nil, err } + gateway.rotation = m.rotation gateway.catalog.SetPricingStore(m.metadata) gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath)) return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil @@ -163,6 +176,21 @@ func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) { func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResult, error) { m.updateMu.Lock() defer m.updateMu.Unlock() + return m.applyLocked(candidate, persist) +} + +// Update serializes read-modify-write operations against the latest config. +func (m *RuntimeManager) Update(change func(*config.Config) error) (ApplyResult, error) { + m.updateMu.Lock() + defer m.updateMu.Unlock() + candidate := m.Config() + if err := change(&candidate); err != nil { + return ApplyResult{}, err + } + return m.applyLocked(candidate, true) +} + +func (m *RuntimeManager) applyLocked(candidate config.Config, persist bool) (ApplyResult, error) { current := m.current.Load() hadPlaintextPassword := candidate.WebUI.Password != "" @@ -185,6 +213,9 @@ func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResu if current != nil { next.gateway.catalog.CopyState(current.gateway.catalog) } + if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil { + return ApplyResult{}, err + } if persist || hadPlaintextPassword { if err := config.SaveAtomic(m.configPath, normalized); err != nil { next.cancel() @@ -208,6 +239,8 @@ func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResu if current == nil || normalized.Logging.RingSize != current.config.Logging.RingSize { m.hub.Resize(normalized.Logging.RingSize) } + m.rotation.Configure(normalized.Rotation) + next.gateway.syncRotation() m.start(next) previous := m.current.Swap(next) if previous != nil { diff --git a/internal/gateway/server_keys_test.go b/internal/gateway/server_keys_test.go new file mode 100644 index 0000000..a44a6ff --- /dev/null +++ b/internal/gateway/server_keys_test.go @@ -0,0 +1,33 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "testing" + + "opencode2api/internal/config" +) + +func TestDisabledServerKeysRejected(t *testing.T) { + g := &Gateway{cfg: config.Config{ServerKeys: []string{"active-secret", "disabled-secret"}, ServerKeyMetadata: map[string]config.ServerKeyMetadata{config.Fingerprint("disabled-secret"): {Disabled: true}}}} + h := g.authenticate(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }) + for _, header := range []string{"Authorization", "x-api-key"} { + for _, key := range []string{"active-secret", "disabled-secret", "unknown"} { + r := httptest.NewRequest("GET", "/v1/models", nil) + value := key + if header == "Authorization" { + value = "Bearer " + key + } + r.Header.Set(header, value) + w := httptest.NewRecorder() + h(w, r) + want := 401 + if key == "active-secret" { + want = 204 + } + if w.Code != want { + t.Errorf("%s status %d want %d", header, w.Code, want) + } + } + } +} diff --git a/internal/protocol/rotation_stream.go b/internal/protocol/rotation_stream.go new file mode 100644 index 0000000..6dbb50e --- /dev/null +++ b/internal/protocol/rotation_stream.go @@ -0,0 +1,95 @@ +package protocol + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" +) + +// StreamFailure carries upstream classification without exposing its raw text +// to the caller or diagnostics. It can be examined before committing a stream. +type StreamFailure struct{ Message, Type string } + +func (e *StreamFailure) Error() string { return "upstream stream failed" } + +type ClientWriteError struct{ Err error } + +func (e *ClientWriteError) Error() string { return "downstream write failed" } +func (e *ClientWriteError) Unwrap() error { return e.Err } + +// RotationStream holds role/start/usage events until useful content or a normal +// terminal event. Ready commits the chosen model and stops the first-output +// timer. Once committed, failures are emitted in-band and never replayed. +func RotationStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, alias string, ready func() error) (usage Usage, reported, committed bool, result error) { + flusher, ok := w.(http.Flusher) + if !ok { + return usage, false, false, fmt.Errorf("streaming is unsupported") + } + parser := newStreamUsageObserver(from).parser + emitter := newBridgeStreamEmitter(w, flusher, to, alias) + pending := []bridgeStreamEvent{} + var upstreamFailure error + emit := func(event bridgeStreamEvent) error { + event.Model = "" // The emitter's model is the requested alias for the whole response. + if err := emitter.Emit(event); err != nil { + if errors.Is(err, errStreamUpstreamFailure) { + return err + } + return &ClientWriteError{err} + } + return nil + } + readErr := readSSE(reader, func(name, data string) error { + events, err := parser.Parse(name, data) + if err != nil { + return &StreamFailure{Type: "parse_error"} + } + for _, event := range events { + if event.Kind == "error" { + upstreamFailure = &StreamFailure{event.Error, event.ErrorType} + return upstreamFailure + } + if !committed { + effective := event.Kind == "text" || event.Kind == "reasoning" || event.Kind == "reasoning_signature" || event.Kind == "tool_start" || event.Kind == "tool_delta" || event.Kind == "done" + if !effective { + if len(pending) >= 256 { + return &StreamFailure{Type: "invalid_prelude"} + } + pending = append(pending, event) + continue + } + if err := ready(); err != nil { + return err + } + committed = true + for _, p := range pending { + if err := emit(p); err != nil { + return err + } + } + pending = nil + } + if err := emit(event); err != nil { + return err + } + if event.Kind == "done" { + return errStreamNormalTermination + } + } + return nil + }) + usage, reported = emitter.usage, emitter.usageReported + if errors.Is(readErr, errStreamNormalTermination) { + return usage, reported, committed, nil + } + if readErr == nil { + readErr = &StreamFailure{Type: "unexpected_eof"} + } + var writeErr *ClientWriteError + if committed && ctx.Err() == nil && !errors.As(readErr, &writeErr) { + _ = emit(bridgeStreamEvent{Kind: "error", Error: "当前上游模型的输出中断;本次响应已结束,请重新发起请求。", ErrorType: "upstream_error"}) + } + return usage, reported, committed, readErr +} diff --git a/internal/rotation/state.go b/internal/rotation/state.go new file mode 100644 index 0000000..9f42417 --- /dev/null +++ b/internal/rotation/state.go @@ -0,0 +1,294 @@ +// Package rotation owns sticky, service-wide model selection. No network call +// runs under its lock. A generation prevents late requests undoing a switch. +package rotation + +import ( + "encoding/json" + "fmt" + "opencode2api/internal/config" + "os" + "path/filepath" + "slices" + "sort" + "sync" + "time" +) + +type Attempt struct { + Time time.Time `json:"time"` + Request string `json:"request"` + Alias string `json:"alias"` + Model string `json:"model"` + Number int `json:"number"` + Outcome string `json:"outcome"` +} +type Switch struct { + Time time.Time `json:"time"` + From string `json:"from"` + To string `json:"to"` + Reason string `json:"reason"` +} +type Group struct { + ID string `json:"id"` + Alias string `json:"alias"` + Order []string `json:"order"` + Current string `json:"current"` + Generation uint64 `json:"generation"` + Paused map[string]time.Time `json:"paused"` + Available map[string]bool `json:"available"` + Switches []Switch `json:"switches"` +} +type Snapshot struct { + Groups []*Group `json:"groups"` + Attempts []Attempt `json:"attempts"` + PersistenceError string `json:"persistence_error,omitempty"` + FirstOutputSeconds int `json:"first_output_seconds"` +} +type Token struct { + Group, Model string + Generation uint64 +} +type Manager struct { + mu sync.Mutex + path string + state Snapshot + cfg config.RotationConfig +} + +func New(path string, cfg config.RotationConfig) (*Manager, error) { + m := &Manager{path: path} + if path != "" { + b, e := os.ReadFile(path) + if e == nil { + if e = json.Unmarshal(b, &m.state); e != nil { + return nil, fmt.Errorf("invalid rotation state: %w", e) + } + } else if !os.IsNotExist(e) { + return nil, e + } + } + if len(m.state.Groups) != 0 && (len(m.state.Groups) != 2 || m.state.Groups[0] == nil || m.state.Groups[1] == nil || m.state.Groups[0].ID != "sota" || m.state.Groups[1].ID != "sweet") { + return nil, fmt.Errorf("invalid rotation groups") + } + m.Configure(cfg) + if m.state.PersistenceError != "" { + return nil, fmt.Errorf("cannot persist rotation state") + } + return m, nil +} +func (m *Manager) Configure(cfg config.RotationConfig) { + m.mu.Lock() + defer m.mu.Unlock() + cfg.Defaults() + for i, c := range []config.RotationGroup{cfg.SOTA, cfg.Sweet} { + id := []string{"sota", "sweet"}[i] + if len(m.state.Groups) <= i { + m.state.Groups = append(m.state.Groups, &Group{ID: id}) + } + g := m.state.Groups[i] + previous := m.cfg.SOTA + if i == 1 { + previous = m.cfg.Sweet + } + order := slices.Clone(g.Order) + if len(order) == 0 || !slices.Equal(previous.Order, c.Order) { + order = slices.Clone(c.Order) + for _, v := range g.Order { + if !slices.Contains(order, v) { + order = append(order, v) + } + } + } + if !slices.Equal(order, g.Order) || g.Alias != c.Alias { + g.Generation++ + } + g.Order = order + g.Alias = c.Alias + if g.Paused == nil { + g.Paused = map[string]time.Time{} + } + if !slices.Contains(g.Order, g.Current) && len(g.Order) > 0 { + g.Current = g.Order[0] + g.Generation++ + } + } + m.cfg = cfg + m.state.FirstOutputSeconds = cfg.FirstOutputSeconds + m.saveLocked() +} +func (m *Manager) Sync(available map[string]bool) { + m.mu.Lock() + defer m.mu.Unlock() + changed := false + for _, g := range m.state.Groups { + g.Available = map[string]bool{} + for model := range available { + if config.IsSOTA(model) == (g.ID == "sota") { + g.Available[model] = true + } + } + added := []string{} + for model := range g.Available { + if !slices.Contains(g.Order, model) { + added = append(added, model) + } + } + sort.Strings(added) + if len(g.Order) == 0 && slices.Contains(added, "glm-5.3-flash") { + added = append([]string{"glm-5.3-flash"}, slices.Delete(added, slices.Index(added, "glm-5.3-flash"), slices.Index(added, "glm-5.3-flash")+1)...) + } + if len(added) > 0 { + g.Order = append(g.Order, added...) + changed = true + } + if g.Current == "" && len(g.Order) > 0 { + g.Current = g.Order[0] + g.Generation++ + changed = true + } + } + if changed { + m.saveLocked() + } +} +func (m *Manager) GroupID(alias string) string { + m.mu.Lock() + defer m.mu.Unlock() + for _, g := range m.state.Groups { + if g.Alias == alias { + return g.ID + } + } + return "" +} +func (m *Manager) Snapshot() Snapshot { + m.mu.Lock() + defer m.mu.Unlock() + b, _ := json.Marshal(m.state) + var s Snapshot + _ = json.Unmarshal(b, &s) + return s +} +func (m *Manager) group(id string) *Group { + for _, g := range m.state.Groups { + if g.ID == id { + return g + } + } + return nil +} +func usable(g *Group, model string) bool { + return g.Available[model] && !time.Now().Before(g.Paused[model]) +} +func (m *Manager) Select(id string, visited map[string]bool) (Token, bool) { + m.mu.Lock() + defer m.mu.Unlock() + g := m.group(id) + if g == nil || len(g.Order) == 0 { + return Token{}, false + } + start := max(slices.Index(g.Order, g.Current), 0) + for n := 0; n < len(g.Order); n++ { + model := g.Order[(start+n)%len(g.Order)] + if visited[model] || !usable(g, model) { + continue + } + // A request-local skip must not change a newer, healthy global selection. + if !usable(g, g.Current) { + m.switchLocked(g, model, "当前模型暂停或已下架") + m.saveLocked() + } + return Token{g.ID, model, g.Generation}, true + } + return Token{}, false +} +func (m *Manager) switchLocked(g *Group, to, reason string) { + from := g.Current + g.Current = to + g.Generation++ + g.Switches = append(g.Switches, Switch{time.Now().UTC(), from, to, reason}) + if len(g.Switches) > 30 { + g.Switches = g.Switches[len(g.Switches)-30:] + } +} +func (m *Manager) Fail(t Token, pause time.Duration, reason string) { + m.mu.Lock() + defer m.mu.Unlock() + g := m.group(t.Group) + if g == nil { + return + } + until := time.Now().Add(pause).UTC() + if until.After(g.Paused[t.Model]) { + g.Paused[t.Model] = until + } + if g.Current == t.Model && g.Generation == t.Generation { + start := slices.Index(g.Order, t.Model) + next := t.Model + for n := 1; n < len(g.Order); n++ { + v := g.Order[(start+n)%len(g.Order)] + if usable(g, v) { + next = v + break + } + } + m.switchLocked(g, next, reason) + } + m.saveLocked() +} +func (m *Manager) Manual(id, model string) error { + m.mu.Lock() + defer m.mu.Unlock() + g := m.group(id) + if g == nil || !slices.Contains(g.Order, model) || !g.Available[model] { + return fmt.Errorf("请选择该组当前可用的 Go 模型") + } + delete(g.Paused, model) + m.switchLocked(g, model, "管理员手动切换") + m.saveLocked() + if m.state.PersistenceError != "" { + return fmt.Errorf("轮转状态保存失败") + } + return nil +} +func (m *Manager) Record(a Attempt) { + m.mu.Lock() + defer m.mu.Unlock() + a.Time = time.Now().UTC() + m.state.Attempts = append(m.state.Attempts, a) + if len(m.state.Attempts) > 100 { + m.state.Attempts = m.state.Attempts[len(m.state.Attempts)-100:] + } + m.saveLocked() +} +func (m *Manager) saveLocked() { + if m.path == "" { + return + } + m.state.PersistenceError = "" + if err := m.writeLocked(); err != nil { + m.state.PersistenceError = "轮转状态写入失败,请检查磁盘空间和文件权限" + } +} +func (m *Manager) writeLocked() error { + b, e := json.MarshalIndent(m.state, "", " ") + if e != nil { + return e + } + f, e := os.CreateTemp(filepath.Dir(m.path), ".rotation-*.tmp") + if e != nil { + return e + } + defer os.Remove(f.Name()) + if _, e = f.Write(b); e == nil { + e = f.Sync() + } + ce := f.Close() + if e == nil { + e = ce + } + if e != nil { + return e + } + return os.Rename(f.Name(), m.path) +} diff --git a/internal/rotation/state_test.go b/internal/rotation/state_test.go new file mode 100644 index 0000000..1566cae --- /dev/null +++ b/internal/rotation/state_test.go @@ -0,0 +1,94 @@ +package rotation + +import ( + "opencode2api/internal/config" + "path/filepath" + "slices" + "sync" + "testing" + "time" +) + +func TestStickyPersistenceMembershipAndGeneration(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + cfg := config.RotationConfig{} + cfg.Defaults() + m, err := New(path, cfg) + if err != nil { + t.Fatal(err) + } + available := map[string]bool{"deepseek-v4.1-flash": true, "glm-5.3": true, "glm-5.3-flash": true, "z-model": true, "a-model": true} + m.Sync(available) + s := m.Snapshot() + if !slices.Equal(s.Groups[1].Order, []string{"glm-5.3-flash", "a-model", "z-model"}) { + t.Fatal(s.Groups[1].Order) + } + first, _ := m.Select("sota", nil) + same, _ := m.Select("sota", nil) + if first != same { + t.Fatal("success should not rotate") + } + m.Fail(first, 15*time.Second, "error") + next, _ := m.Select("sota", nil) + if next.Model != "glm-5.3" { + t.Fatal(next) + } + // Old inflight failures cannot undo a manual selection (nor can successes). + if err := m.Manual("sota", "deepseek-v4.1-flash"); err != nil { + t.Fatal(err) + } + before := m.Snapshot().Groups[0].Generation + var wg sync.WaitGroup + for i := 0; i < 20; i++ { + wg.Add(1) + go func() { defer wg.Done(); m.Fail(first, time.Second, "stale"); m.Snapshot() }() + } + wg.Wait() + s = m.Snapshot() + if s.Groups[0].Current != "deepseek-v4.1-flash" || s.Groups[0].Generation != before { + t.Fatal("stale completion moved cursor") + } + // Reordering config and key-only reloads keep operational state. + cfg.Sweet.Order = []string{"z-model", "a-model", "glm-5.3-flash"} + m.Configure(cfg) + available["0-new-model"] = true + delete(available, "a-model") + m.Sync(available) + m2, err := New(path, cfg) + if err != nil { + t.Fatal(err) + } + m2.Sync(available) + s = m2.Snapshot() + if !slices.Equal(s.Groups[1].Order, []string{"z-model", "a-model", "glm-5.3-flash", "0-new-model"}) { + t.Fatal(s.Groups[1].Order) + } + if s.Groups[1].Available["a-model"] { + t.Fatal("delisted model available") + } + if s.Groups[0].Paused[first.Model].IsZero() { + t.Fatal("pause not persisted") + } + if s.Groups[0].Current != "deepseek-v4.1-flash" { + t.Fatal("current not persisted") + } +} +func TestNoWrapDuplicatesAndUnavailable(t *testing.T) { + m, _ := New("", config.RotationConfig{}) + m.Sync(map[string]bool{"glm-5.3": true, "kimi-k3": true}) + visited := map[string]bool{} + for i := 0; i < 2; i++ { + token, ok := m.Select("sota", visited) + if !ok { + t.Fatal(i) + } + visited[token.Model] = true + m.Fail(token, time.Minute, "quota") + } + if _, ok := m.Select("sota", visited); ok { + t.Fatal("revisited model") + } + if _, ok := m.Select("sota", nil); ok { + t.Fatal("paused model selected") + } +} diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index 75758a9..36f5f92 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -12,19 +12,20 @@ import ( ) type RequestMeta struct { - Model string - Tier string - Protocol protocol.Protocol - Request string - KeyID string - Channel string - Anonymous bool - Proxy string - Attempts int - Legs []string - Stop string - Tail string - Stream bool + ModelAlias string + Model string + Tier string + Protocol protocol.Protocol + Request string + KeyID string + Channel string + Anonymous bool + Proxy string + Attempts int + Legs []string + Stop string + Tail string + Stream bool // Shaped marks a key-tier free-model request whose wire body was // normalized to agent shape (stream + core tools) like the anonymous // lane. Non-streaming responses for shaped requests arrive as SSE @@ -111,13 +112,13 @@ func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.H if meta.Channel != "" { logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request, - "model", meta.Model, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, + "model", meta.Model, "model_alias", meta.ModelAlias, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome, "stop", meta.Stop, "in", meta.Usage.Input, "out", meta.Usage.Output, "reasoning_tokens", meta.Usage.Reasoning, "cached", meta.Usage.Cached, "tail", meta.Tail) } logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes, - "request_id", meta.Request, "model", meta.Model, "tier", meta.Tier, "key_id", meta.KeyID, + "request_id", meta.Request, "model", meta.Model, "model_alias", meta.ModelAlias, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream, "outcome", outcome) }() next.ServeHTTP(writer, r) diff --git a/webui/app.js b/webui/app.js index 3d5419b..eac26dd 100644 --- a/webui/app.js +++ b/webui/app.js @@ -12,6 +12,7 @@ let csrf = "", logRenderPending = false, toastTimer = null; const pages = { + rotation: ["12", "模型轮转", "共享当前模型、故障切换与尝试记录。"], overview: ["01", "运行桌面", "最近一小时、进程累计与当前资源状态。"], guide: ["02", "首次运行", "用六个检查点完成从配置到首个请求。"], access: ["03", "接入手册", "Chat、Responses、Anthropic 与 SDK 示例。"], @@ -21,6 +22,8 @@ const pages = { config: ["07", "配置中心", "验证后原子保存,并热应用可变字段。"], logs: ["08", "事件日志", "来自进程内 Ring Buffer 的结构化 SSE。"], account: ["09", "账号安全", "更新后撤销全部管理 Session。"], + "model-quotas": ["10", "模型与额度", "可用模型、共享套餐剩余额度与重置时间。"], + "api-keys": ["11", "API Key 管理", "给每个调用方独立的访问密钥。"], }; async function api(path, options = {}) { options.headers = { ...(options.headers || {}), Accept: "application/json" }; @@ -52,6 +55,9 @@ function showLogin() { if (eventSource) eventSource.close(); eventSource = null; clearInterval(monitorTimer); + clearInterval(quotaTimer); + clearCreatedKey(); + $("#api-key-value").value = ""; } async function enterConsole(session) { csrf = session.csrf_token; @@ -62,6 +68,7 @@ async function enterConsole(session) { clearInterval(monitorTimer); monitorTimer = setInterval(refreshMonitor, 3000); connectLogs(); + openPage(pages[location.hash.slice(1)] ? location.hash.slice(1) : "overview"); } async function boot() { try { @@ -92,6 +99,10 @@ $("#logout").onclick = async () => { } }; function openPage(page) { + if (!pages[page]) return; + history.replaceState(null, "", `#${page}`); + clearInterval(quotaTimer); + if (page !== "api-keys") clearCreatedKey(); $$(".nav button").forEach((button) => button.classList.toggle("active", button.dataset.page === page), ); @@ -102,6 +113,14 @@ function openPage(page) { $("#page-sub").textContent = meta[2]; if (page === "access") renderAccessExamples(); if (page === "usage") renderUsage(); + if (page === "model-quotas") { + loadModelQuotas(); + quotaTimer = setInterval(() => { + if (!document.hidden) loadModelQuotas(); + }, 60000); + } + if (page === "rotation") loadRotation(); + if (page === "api-keys") loadAPIKeys(); if (page === "playground" && !debugData) loadDebugModels(); if (page === "diagnostics") { loadDebugModels(); @@ -769,6 +788,8 @@ async function refreshMonitor() { } $("#refresh-now").onclick = async () => { await Promise.all([refreshMonitor(), loadConfig(), loadDebugModels()]); + if (location.hash === "#model-quotas") await loadModelQuotas(); + if (location.hash === "#api-keys") await loadAPIKeys(); toast("状态已刷新"); }; function derivedAPIBase() { @@ -910,4 +931,455 @@ $("#log-pause").onclick = () => { $("#log-pause").textContent = paused ? "继续" : "暂停"; if (!paused) renderLogs(); }; +let quotaData = null, + quotaTimer = null, + quotaLoading = false, + createdKey = "", + apiKeysLoading = false; +const localTime = (value) => + value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "—"; + +function clearCreatedKey() { + createdKey = ""; + $("#api-key-env").textContent = ""; + $("#api-key-created").classList.add("hidden"); +} + +async function copyText(text) { + try { + await navigator.clipboard.writeText(text); + toast("已复制"); + } catch { + toast("浏览器未允许复制,请手动选中复制", true); + } +} + +async function loadModelQuotas() { + if (quotaLoading) return; + quotaLoading = true; + $("#quota-refresh").disabled = true; + $("#quota-refresh").textContent = "读取中…"; + try { + const value = await api("/api/model-quotas"); + if (!csrf) return; + quotaData = value; + const select = $("#quota-account"), + selected = select.value; + select.replaceChildren(); + for (const account of value.accounts || []) { + const option = document.createElement("option"); + option.value = account.id; + option.textContent = `Go Key ${account.display}`; + select.appendChild(option); + } + if ([...select.options].some((option) => option.value === selected)) select.value = selected; + if (!select.options.length) select.appendChild(new Option("尚未配置 Go Key", "")); + renderModelQuotas(); + } catch (error) { + $("#quota-status").textContent = `查询失败:${error.message}。已有显示仅为上次查询结果。`; + } finally { + quotaLoading = false; + $("#quota-refresh").disabled = false; + $("#quota-refresh").textContent = "刷新额度"; + } +} + +function renderModelQuotas() { + if (!quotaData) return; + const account = quotaData.accounts.find((item) => item.id === $("#quota-account").value); + const stale = account?.status === "stale"; + const cards = $("#quota-cards"); + cards.replaceChildren(); + $("#quota-status").textContent = !account + ? "请先在配置中心添加 OpenCode Go Key。" + : account.error + ? `${account.error}${stale ? ";下方显示上次成功数据,当前额度未知。" : ";当前额度未知。"}` + : "已连接 OpenCode · 共享套餐额度。多个 Key 的额度不相加。"; + $("#quota-updated").textContent = account?.fetched_at + ? `${stale ? "上次成功查询" : "额度更新时间"}:${localTime(account.fetched_at)} · 缓存 60 秒 · 来源:OpenCode Go /v1/usage` + : ""; + const windows = [ + ["rolling", "5 小时窗口"], + ["weekly", "每周窗口"], + ["monthly", "每月窗口"], + ]; + for (const [id, label] of windows) { + const item = account?.windows?.[id]; + const card = document.createElement("div"), + heading = document.createElement("h3"), + value = document.createElement("div"), + progress = document.createElement("progress"), + reset = document.createElement("div"); + card.className = `quota-card${item?.remaining_percent < 20 ? " quota-low" : ""}`; + heading.textContent = label; + value.className = "quota-value"; + value.textContent = item ? `≈ ${item.remaining_percent}%` : "未知"; + progress.max = 100; + if (item) progress.value = item.remaining_percent; + else progress.value = 0; + progress.setAttribute("aria-label", `${label}剩余额度`); + reset.className = "quota-reset"; + reset.textContent = item + ? `${stale ? "历史剩余" : "剩余"} · ${item.status === "rate-limited" ? "已限额 · " : ""}重置于 ${localTime(item.resets_at)}` + : "等待上游额度数据"; + card.append(heading, value, progress, reset); + cards.appendChild(card); + } + const query = $("#quota-model-search").value.trim().toLowerCase(); + const models = quotaData.models.filter((model) => model.id.toLowerCase().includes(query)); + $("#quota-model-count").textContent = `${models.length} / ${quotaData.models.length}`; + const catalog = quotaData.catalog; + $("#quota-catalog-status").textContent = + `${catalog?.stale ? "模型目录暂未更新,显示缓存 · " : ""}目录更新时间:${localTime(catalog?.updated_at)}`; + const host = $("#quota-models"); + host.replaceChildren(); + for (const model of models) { + const row = document.createElement("tr"); + appendCell(row, model.id, "mono"); + appendCell( + row, + { chat: "Chat Completions", responses: "Responses", anthropic: "Messages" }[model.protocol] || + model.protocol, + ); + for (const [id] of windows) { + const item = account?.windows?.[id]; + appendCell(row, item ? `≈ ${item.remaining_percent}%${stale ? "(历史)" : ""}` : "未知"); + } + const cell = document.createElement("td"), + button = document.createElement("button"); + button.className = "ghost"; + button.textContent = "复制名称"; + button.onclick = () => copyText(model.id); + cell.appendChild(button); + row.appendChild(cell); + host.appendChild(row); + } + if (!models.length) + emptyRow(host, 6, quotaData.models.length ? "没有匹配的模型" : "模型目录尚未就绪,请稍后刷新"); +} +$("#quota-refresh").onclick = loadModelQuotas; +$("#quota-account").onchange = renderModelQuotas; +$("#quota-model-search").oninput = renderModelQuotas; + +async function loadAPIKeys() { + if (apiKeysLoading) return; + apiKeysLoading = true; + $("#api-key-refresh").disabled = true; + try { + const data = await api("/api/api-keys"); + if (csrf) renderAPIKeys(data.keys); + } catch (error) { + $("#api-key-status").textContent = `读取失败:${error.message}`; + } finally { + apiKeysLoading = false; + $("#api-key-refresh").disabled = false; + } +} + +async function mutateAPIKey(id, method, body, button) { + button.disabled = true; + try { + const data = await api(`/api/api-keys/${encodeURIComponent(id)}`, { + method, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + if (!csrf) return; + renderAPIKeys(data.keys); + await loadConfig(); + toast("已保存并立即生效"); + } catch (error) { + toast(error.message, true); + } finally { + button.disabled = false; + } +} + +function renderAPIKeys(keys) { + $("#api-key-count").textContent = `${keys.length} 个`; + $("#api-key-status").textContent = `${keys.filter((key) => key.enabled).length} 个已启用`; + const host = $("#api-key-list"); + host.replaceChildren(); + for (const key of keys) { + const row = document.createElement("tr"); + appendCell(row, key.name); + appendCell(row, key.display, "mono"); + appendCell(row, key.enabled ? "已启用" : "已停用", key.enabled ? "status ok" : "status warn"); + appendCell(row, key.created_at ? localTime(key.created_at) : "已有配置"); + const cell = document.createElement("td"), + actions = document.createElement("div"); + actions.className = "key-actions"; + for (const [label, action] of [ + [ + "重命名", + (button) => { + const name = prompt("密钥名称", key.name); + if (name !== null) mutateAPIKey(key.id, "PATCH", { name }, button); + }, + ], + [ + key.enabled ? "停用" : "启用", + (button) => mutateAPIKey(key.id, "PATCH", { enabled: !key.enabled }, button), + ], + [ + "删除", + (button) => { + if (confirm(`删除“${key.name}”后,使用它的应用将无法继续访问。确定删除?`)) + mutateAPIKey(key.id, "DELETE", null, button); + }, + ], + ]) { + const button = document.createElement("button"); + button.className = "ghost"; + button.textContent = label; + button.onclick = () => action(button); + actions.appendChild(button); + } + cell.appendChild(actions); + row.appendChild(cell); + host.appendChild(row); + } + if (!keys.length) emptyRow(host, 5, "暂无 API Key"); +} +$("#api-key-form").onsubmit = async (event) => { + event.preventDefault(); + const button = $("#api-key-create"); + button.disabled = true; + try { + const data = await api("/api/api-keys", { + method: "POST", + body: JSON.stringify({ name: $("#api-key-name").value, value: $("#api-key-value").value }), + }); + if (!csrf) return; + createdKey = data.key; + const goModels = debugData?.models?.filter((item) => item.available_go) || []; + const model = + goModels.find((item) => item.model === "glm-5.3-flash")?.model || + goModels[0]?.model || + "YOUR_MODEL"; + $("#api-key-env").textContent = + `OPENAI_API_KEY=${data.key}\nOPENAI_BASE_URL=${derivedAPIBase()}/v1\nOPENAI_MODEL=${model}`; + $("#api-key-created").classList.remove("hidden"); + $("#api-key-form").reset(); + renderAPIKeys(data.keys); + await loadConfig(); + toast("API Key 已创建"); + } catch (error) { + toast(error.message, true); + } finally { + button.disabled = false; + } +}; +$("#api-key-refresh").onclick = loadAPIKeys; +$("#api-key-dismiss").onclick = clearCreatedKey; +$("#api-key-copy").onclick = () => copyText(createdKey); +$("#api-key-copy-env").onclick = () => copyText($("#api-key-env").textContent); +let rotationData = null, + rotationDirty = false; +const rotationReasons = { + success: "成功", + client_canceled: "调用方取消", + quota_or_rate_limit: "额度不足 / 限流", + transport_error: "连接错误", + first_output_timeout: "首个输出超时", + stream_error: "输出中断", + response_read_error: "读取响应失败", + response_conversion_error: "响应解析或转换失败", + request_conversion_error: "请求转换失败", + upstream_error: "上游错误", +}; +async function loadRotation() { + try { + const value = await api("/api/rotation"); + if (!csrf) return; + rotationData = value; + rotationDirty = false; + renderRotation(); + } catch (error) { + toast(error.message, true); + } +} +function renderRotation() { + const state = rotationData; + $("#rotation-status").textContent = + state.persistence_error || "状态已更新 · 两组独立轮转,所有调用方共享当前位置。"; + $("#rotation-timeout").value = state.first_output_seconds; + const host = $("#rotation-groups"); + host.replaceChildren(); + for (const group of state.groups) { + const section = document.createElement("div"); + section.className = "section"; + const title = document.createElement("h2"); + title.textContent = group.id === "sota" ? "SOTA" : "甜点"; + const label = document.createElement("label"); + label.textContent = "调用别名"; + label.htmlFor = `rotation-alias-${group.id}`; + const input = document.createElement("input"); + input.id = label.htmlFor; + input.value = group.alias; + input.required = true; + input.maxLength = 64; + input.oninput = () => { + group.alias = input.value; + rotationDirty = true; + }; + const field = document.createElement("div"); + field.className = "field"; + field.append(label, input); + const current = document.createElement("p"); + current.className = "mono"; + current.textContent = `当前模型:${group.current || "等待可用模型"}`; + const table = document.createElement("table"); + table.className = "table"; + const header = document.createElement("tr"); + for (const text of ["顺序", "模型", "状态 / 恢复时间", "操作"]) { + const th = document.createElement("th"); + th.textContent = text; + header.append(th); + } + const thead = document.createElement("thead"); + thead.append(header); + table.append(thead); + const tbody = document.createElement("tbody"); + table.append(tbody); + group.order.forEach((model, index) => { + const row = document.createElement("tr"); + appendCell(row, String(index + 1)); + appendCell(row, model, "mono"); + const until = group.paused[model], + paused = until && new Date(until) > new Date(); + appendCell( + row, + !group.available[model] + ? "已下架 / 暂不可用" + : paused + ? `暂停至 ${localTime(until)}` + : model === group.current + ? "当前使用" + : "可用", + ); + const actions = document.createElement("td"); + actions.className = "rotation-actions"; + for (const [text, delta] of [ + ["上移", -1], + ["下移", 1], + ]) { + const button = document.createElement("button"); + button.type = "button"; + button.className = "ghost"; + button.textContent = text; + button.setAttribute("aria-label", `${model} ${text}`); + button.disabled = index + delta < 0 || index + delta >= group.order.length; + button.onclick = () => { + [group.order[index], group.order[index + delta]] = [ + group.order[index + delta], + group.order[index], + ]; + state.first_output_seconds = Number($("#rotation-timeout").value); + rotationDirty = true; + renderRotation(); + }; + actions.append(button); + } + const select = document.createElement("button"); + select.type = "button"; + select.className = "ghost"; + select.textContent = "设为当前"; + select.disabled = !group.available[model]; + select.setAttribute("aria-label", `使用 ${model}`); + select.onclick = async () => { + select.disabled = true; + try { + const result = await api("/api/rotation/current", { + method: "POST", + body: JSON.stringify({ group: group.id, model }), + }); + // Keep unsaved alias/order edits while refreshing operational state. + for (const item of state.groups) { + const live = result.groups.find((x) => x.id === item.id); + Object.assign(item, { + current: live.current, + paused: live.paused, + switches: live.switches, + }); + } + state.persistence_error = result.persistence_error; + renderRotation(); + toast("当前模型已切换"); + } catch (error) { + select.disabled = false; + toast(error.message, true); + } + }; + actions.append(select); + row.append(actions); + tbody.append(row); + }); + if (!group.order.length) emptyRow(tbody, 4, "等待 Go 模型目录"); + const wrap = document.createElement("div"); + wrap.className = "table-wrap"; + wrap.append(table); + const recent = document.createElement("div"); + recent.className = "rotation-switches"; + const caption = document.createElement("h3"); + caption.textContent = "最近切换"; + recent.append(caption); + for (const item of (group.switches || []).slice(-5).reverse()) { + const line = document.createElement("p"); + line.textContent = `${localTime(item.time)} · ${item.from} → ${item.to} · ${rotationReasons[item.reason] || item.reason}`; + recent.append(line); + } + if (!group.switches?.length) { + const line = document.createElement("p"); + line.textContent = "尚无切换记录"; + recent.append(line); + } + section.append(title, field, current, wrap, recent); + host.append(section); + } + const attempts = $("#rotation-attempts"); + attempts.replaceChildren(); + for (const item of (state.attempts || []).slice().reverse()) { + const row = document.createElement("tr"); + for (const value of [ + localTime(item.time), + item.request, + item.alias, + item.model, + String(item.number), + rotationReasons[item.outcome] || item.outcome, + ]) + appendCell(row, value); + attempts.append(row); + } + if (!state.attempts?.length) emptyRow(attempts, 6, "调用分组别名后显示最近 100 次尝试"); +} +$("#rotation-refresh").onclick = () => { + if (rotationDirty) { + toast("有未保存的修改,请先保存后刷新", true); + return; + } + loadRotation(); +}; +$("#rotation-timeout").oninput = () => { + rotationDirty = true; +}; +$("#rotation-form").onsubmit = async (event) => { + event.preventDefault(); + if (!rotationData) return; + const button = $("#rotation-save"); + button.disabled = true; + try { + const body = { first_output_seconds: Number($("#rotation-timeout").value) }; + for (const group of rotationData.groups) + body[group.id] = { alias: group.alias.trim(), order: group.order }; + rotationData = await api("/api/rotation", { method: "PUT", body: JSON.stringify(body) }); + rotationDirty = false; + renderRotation(); + toast("模型轮转配置已保存并生效"); + } catch (error) { + toast(error.message, true); + } finally { + button.disabled = false; + } +}; boot(); diff --git a/webui/index.html b/webui/index.html index b4973e5..743b861 100644 --- a/webui/index.html +++ b/webui/index.html @@ -59,6 +59,13 @@ + + +
+ + +