feat: 新增模型轮转、额度看板和密钥管理

This commit is contained in:
haverainlilili committed 2026-09-21 10:18:21 +08:00
1 parent e5f4e3a583
commit 3440273f43
32 files changed
+2918 -32

No files matched your search

+174
View File
@@ -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)
}
+65
View File
@@ -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")
}
}
}
+2 -2
View File
@@ -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}))
}
+171
View File
@@ -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 可能属于同一套餐,不能相加。百分比由上游取整。",
})
}
+74
View File
@@ -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")
}
}
+63
View File
@@ -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)
}
+13 -1
View File
@@ -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)))
@@ -181,7 +191,9 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
return
}
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,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
}
+30 -14
View File
@@ -16,20 +16,22 @@ 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"`
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"`
effectiveProxies []string
}
@@ -132,6 +134,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)
@@ -156,6 +162,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")
}
@@ -241,7 +250,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...)
+63
View File
@@ -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
}
+32
View File
@@ -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")
}
}
+24
View File
@@ -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 ""
}
+15
View File
@@ -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,
@@ -83,6 +91,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
@@ -122,6 +133,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
+3
View File
@@ -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})
}
+1
View File
@@ -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)
+359
View File
@@ -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
}
+373
View File
@@ -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)
}
})
}
}
+33
View File
@@ -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 {
+33
View File
@@ -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)
}
}
}
}
+95
View File
@@ -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
}
+294
View File
@@ -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)
}
+94
View File
@@ -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")
}
}
+16 -15
View File
@@ -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)