mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-06 00:03:11 +00:00
发布准备:合入 #36、#46、#48、#49、#50、#53;修复 #42、#44、#51、#52,并添加 GPL-3.0-or-later。
保留 reasoning 配置,新增免费模型可用性探测 / 手动恢复、首 SSE 事件超时,元数据改用官方地址。按维护者要求,最终文件树排除测试文件。 验证:本地 Go 回归、go vet / build、Prettier、JS / shell 语法及独立实例管理端验收通过。
This commit is contained in:
1 parent
31c35704be
commit
df119c48e4
29 files changed
+1301
-807
No files matched your search
@@ -1,65 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"opencode2api/internal/httpx"
|
||||
)
|
||||
|
||||
func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()})
|
||||
}
|
||||
|
||||
func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, 400, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
if err := a.manager.RestoreModel(input.Model); err != nil {
|
||||
writeAdminError(w, 400, "restore_failed", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
a.handleAvailability(w, r)
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ 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/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
|
||||
mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
|
||||
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))))
|
||||
|
||||
@@ -85,13 +85,14 @@ type WebUIConfig struct {
|
||||
}
|
||||
|
||||
type PerformanceConfig struct {
|
||||
MaxIdleConns int `json:"max_idle_conns"`
|
||||
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
|
||||
MaxConnsPerHost int `json:"max_conns_per_host"`
|
||||
IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"`
|
||||
ConnectTimeoutSeconds int `json:"connect_timeout_seconds"`
|
||||
FailureCooldownSeconds int `json:"failure_cooldown_seconds"`
|
||||
AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"`
|
||||
MaxIdleConns int `json:"max_idle_conns"`
|
||||
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
|
||||
MaxConnsPerHost int `json:"max_conns_per_host"`
|
||||
IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"`
|
||||
ConnectTimeoutSeconds int `json:"connect_timeout_seconds"`
|
||||
FailureCooldownSeconds int `json:"failure_cooldown_seconds"`
|
||||
AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"`
|
||||
FirstEventTimeoutSeconds int `json:"first_event_timeout_seconds"`
|
||||
}
|
||||
|
||||
// AttemptTimeout bounds how long a single upstream attempt may wait for
|
||||
@@ -198,6 +199,9 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
if cfg.Performance.AttemptTimeoutSeconds < 0 {
|
||||
return Config{}, errors.New("performance.attempt_timeout_seconds must not be negative (0 keeps the retry timeout)")
|
||||
}
|
||||
if cfg.Performance.FirstEventTimeoutSeconds < 0 || cfg.Performance.FirstEventTimeoutSeconds > 86400 {
|
||||
return Config{}, errors.New("performance.first_event_timeout_seconds must be between 0 and 86400 (0 disables the first-event timeout)")
|
||||
}
|
||||
if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" {
|
||||
return Config{}, errors.New("logging.level must be debug, info, warn, or error")
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/identity"
|
||||
"opencode2api/internal/models"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability {
|
||||
items := []models.Availability{}
|
||||
r := m.current.Load()
|
||||
if r == nil {
|
||||
return items
|
||||
}
|
||||
for _, model := range r.gateway.catalog.List() {
|
||||
if r.gateway.catalog.IsFreeModel(model) {
|
||||
items = append(items, r.availability.Get(model))
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) RestoreModel(model string) error {
|
||||
m.updateMu.Lock()
|
||||
defer m.updateMu.Unlock()
|
||||
for _, item := range m.AvailabilitySnapshot() {
|
||||
if item.Model == model {
|
||||
return m.current.Load().availability.Restore(model, time.Now().UTC())
|
||||
}
|
||||
}
|
||||
return errors.New("unknown free model")
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) startAvailabilityChecks() {
|
||||
ctx, cancel := context.WithCancel(m.root)
|
||||
m.availabilityCancel = cancel
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
m.checkFreeModels(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) checkFreeModels(ctx context.Context) {
|
||||
for _, item := range m.AvailabilitySnapshot() {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
r := m.current.Load()
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
item = r.availability.Get(item.Model)
|
||||
if time.Now().Before(item.NextCheck) {
|
||||
continue
|
||||
}
|
||||
ok, reason, channel, attempted := r.gateway.probeFreeModel(ctx, item.Model)
|
||||
if !attempted || ctx.Err() != nil {
|
||||
continue
|
||||
}
|
||||
// Config changes may replace credentials or endpoints during a probe.
|
||||
m.updateMu.Lock()
|
||||
if m.current.Load() == r {
|
||||
if err := r.availability.Record(item.Model, item.Generation, ok, reason, channel, time.Now().UTC()); err != nil {
|
||||
m.logger.Warn("model availability state save failed", "error", err)
|
||||
}
|
||||
m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", ok, "reason", reason, "channel", channel)
|
||||
}
|
||||
m.updateMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) probeFreeModel(ctx context.Context, model string) (success bool, reason, channel string, attempted bool) {
|
||||
if !g.catalog.IsFreeModel(model) {
|
||||
return false, "not_free", "", false
|
||||
}
|
||||
d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
|
||||
protocol := d.NativeProtocols[config.TierZen]
|
||||
if !d.AvailableZen || !g.catalog.Supported(model) || protocol == wire.SystemOne {
|
||||
return false, "unsupported_probe", "", false
|
||||
}
|
||||
payload := map[string]any{"model": model, "stream": true, "max_tokens": 64, "messages": []any{map[string]any{"role": "user", "content": "Reply with OK."}}}
|
||||
converted, err := wire.ConvertRequest(wire.Chat, protocol, payload)
|
||||
if err != nil {
|
||||
return false, "request_conversion_error", "", false
|
||||
}
|
||||
b, err := json.Marshal(converted)
|
||||
if err != nil {
|
||||
return false, "request_conversion_error", "", false
|
||||
}
|
||||
b = prepareAnonymousBody(b, protocol)
|
||||
type lane struct {
|
||||
key, name string
|
||||
client *http.Client
|
||||
}
|
||||
var lanes []lane
|
||||
if g.cfg.Anonymous {
|
||||
cursor := g.anonymous.CursorFor("availability:" + model)
|
||||
if node := cursor.Next(); node != nil {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", node.proxy.client})
|
||||
}
|
||||
}
|
||||
cursor := g.zenNodes.CursorFor("availability:" + model)
|
||||
if node := cursor.Next(); node != nil {
|
||||
if proxy := g.zenNodes.Proxy(node); proxy != nil {
|
||||
lanes = append(lanes, lane{node.key, "zen", proxy.client})
|
||||
}
|
||||
}
|
||||
for _, lane := range lanes {
|
||||
if ctx.Err() != nil {
|
||||
return false, "canceled", "", false
|
||||
}
|
||||
attempted, channel = true, lane.name
|
||||
probeCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
req, err := newUpstreamRequest(probeCtx, g.cfg.Upstream.Zen, protocol, b, identity.RequestIDs{Session: "availability:" + model}, lane.key)
|
||||
if err == nil {
|
||||
// Probe traffic never updates production key/proxy cooldowns or usage.
|
||||
var resp *http.Response
|
||||
resp, err = lane.client.Do(req)
|
||||
if err == nil {
|
||||
reason = fmt.Sprintf("http_%d", resp.StatusCode)
|
||||
if resp.StatusCode/100 == 2 {
|
||||
if strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
|
||||
_, err = wire.CollapseStream(io.LimitReader(resp.Body, 1<<20), protocol, model)
|
||||
} else {
|
||||
var document map[string]any
|
||||
err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&document)
|
||||
if err == nil && (document == nil || document["error"] != nil) {
|
||||
err = errors.New("invalid response")
|
||||
}
|
||||
if err == nil {
|
||||
field := "choices"
|
||||
if protocol == wire.Anthropic {
|
||||
field = "content"
|
||||
} else if protocol == wire.Responses {
|
||||
field = "output"
|
||||
}
|
||||
if _, ok := document[field].([]any); !ok {
|
||||
err = errors.New("invalid response schema")
|
||||
}
|
||||
}
|
||||
}
|
||||
success = err == nil
|
||||
if !success {
|
||||
reason = "invalid_or_incomplete_response"
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
} else {
|
||||
reason = "transport_error"
|
||||
}
|
||||
}
|
||||
if probeCtx.Err() != nil {
|
||||
success = false
|
||||
reason = "probe_timeout"
|
||||
}
|
||||
cancel()
|
||||
if success {
|
||||
return true, "probe_succeeded", channel, true
|
||||
}
|
||||
}
|
||||
return success, reason, channel, attempted
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errFirstEventTimeout = fmt.Errorf("upstream first SSE event timed out: %w", context.DeadlineExceeded)
|
||||
|
||||
type attemptBody struct {
|
||||
io.Reader
|
||||
body io.ReadCloser
|
||||
cancel context.CancelCauseFunc
|
||||
}
|
||||
|
||||
func (b *attemptBody) Close() error {
|
||||
b.cancel(nil)
|
||||
return b.body.Close()
|
||||
}
|
||||
|
||||
// Wait before returning a successful SSE response to the retry loop, while
|
||||
// nothing has been committed downstream. Keep every byte for native forwarding.
|
||||
// Comments and incomplete frames do not count as the first event.
|
||||
func doInferenceAttempt(client *http.Client, req *http.Request, timeout time.Duration) (*http.Response, error) {
|
||||
if timeout <= 0 || strings.HasSuffix(req.URL.Path, "/systemone") {
|
||||
return client.Do(req)
|
||||
}
|
||||
ctx, cancel := context.WithCancelCause(req.Context())
|
||||
resp, err := client.Do(req.Clone(ctx))
|
||||
if err != nil {
|
||||
cancel(nil)
|
||||
return resp, err
|
||||
}
|
||||
if resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
|
||||
resp.Body = &attemptBody{Reader: resp.Body, body: resp.Body, cancel: cancel}
|
||||
return resp, nil
|
||||
}
|
||||
timer := time.AfterFunc(timeout, func() { cancel(errFirstEventTimeout) })
|
||||
reader := bufio.NewReader(resp.Body)
|
||||
prefix, err := readFirstEvent(reader)
|
||||
stopped := timer.Stop()
|
||||
if !stopped && ctx.Err() == nil {
|
||||
// Stop(false) means the callback may still be about to run.
|
||||
cancel(errFirstEventTimeout)
|
||||
}
|
||||
if cause := context.Cause(ctx); cause != nil {
|
||||
err = cause
|
||||
}
|
||||
if err != nil {
|
||||
cancel(nil)
|
||||
resp.Body.Close()
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &attemptBody{Reader: io.MultiReader(bytes.NewReader(prefix), reader), body: resp.Body, cancel: cancel}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func readFirstEvent(reader *bufio.Reader) ([]byte, error) {
|
||||
const maxPrelude = 1 << 20
|
||||
var prefix, line []byte
|
||||
hasData := false
|
||||
for {
|
||||
part, err := reader.ReadSlice('\n')
|
||||
if len(prefix)+len(part) > maxPrelude {
|
||||
return nil, errors.New("upstream SSE prelude exceeds 1 MiB")
|
||||
}
|
||||
prefix = append(prefix, part...)
|
||||
line = append(line, part...)
|
||||
if errors.Is(err, bufio.ErrBufferFull) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
text := strings.TrimSuffix(strings.TrimSuffix(string(line), "\n"), "\r")
|
||||
line = line[:0]
|
||||
if text == "" && hasData {
|
||||
return prefix, nil
|
||||
}
|
||||
if strings.HasPrefix(text, "data:") || text == "data" {
|
||||
hasData = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,6 +245,9 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans
|
||||
// route is unavailable. HTTP responses and unrelated transport/protocol errors
|
||||
// must not evict a proxy.
|
||||
func isProxyFailure(err error) bool {
|
||||
if errors.Is(err, errFirstEventTimeout) {
|
||||
return false // The upstream accepted HTTP; slow generation is not a broken proxy.
|
||||
}
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+35
-17
@@ -18,10 +18,11 @@ import (
|
||||
)
|
||||
|
||||
type gatewayRuntime struct {
|
||||
config config.Config
|
||||
gateway *Gateway
|
||||
handler http.Handler
|
||||
cancel context.CancelFunc
|
||||
availability *modelcatalog.AvailabilityStore
|
||||
config config.Config
|
||||
gateway *Gateway
|
||||
handler http.Handler
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type ApplyResult struct {
|
||||
@@ -31,18 +32,19 @@ type ApplyResult struct {
|
||||
}
|
||||
|
||||
type RuntimeManager struct {
|
||||
rotation *rotation.Manager
|
||||
configPath string
|
||||
root context.Context
|
||||
logger *slog.Logger
|
||||
monitor *telemetry.Monitor
|
||||
hub *telemetry.LogHub
|
||||
redactor *config.SecretRedactor
|
||||
level *slog.LevelVar
|
||||
current atomic.Pointer[gatewayRuntime]
|
||||
updateMu sync.Mutex
|
||||
effective effectiveListeners
|
||||
metadata *modelcatalog.PricingStore
|
||||
rotation *rotation.Manager
|
||||
configPath string
|
||||
root context.Context
|
||||
logger *slog.Logger
|
||||
monitor *telemetry.Monitor
|
||||
hub *telemetry.LogHub
|
||||
redactor *config.SecretRedactor
|
||||
level *slog.LevelVar
|
||||
current atomic.Pointer[gatewayRuntime]
|
||||
updateMu sync.Mutex
|
||||
effective effectiveListeners
|
||||
metadata *modelcatalog.PricingStore
|
||||
availabilityCancel context.CancelFunc
|
||||
}
|
||||
|
||||
type effectiveListeners struct {
|
||||
@@ -110,6 +112,7 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi
|
||||
telemetry.SetLogLevel(manager.level, cfg.Logging.Level)
|
||||
manager.start(runtime)
|
||||
manager.metadata.Start(root)
|
||||
manager.startAvailabilityChecks()
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
@@ -119,9 +122,21 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) {
|
||||
return nil, err
|
||||
}
|
||||
gateway.rotation = m.rotation
|
||||
availabilityPath := ""
|
||||
if m.configPath != "" {
|
||||
availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json"
|
||||
}
|
||||
availability, err := modelcatalog.NewAvailabilityStore(availabilityPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load model availability: %w", err)
|
||||
}
|
||||
if current := m.current.Load(); current != nil && current.config.Upstream.Zen == cfg.Upstream.Zen {
|
||||
availability = current.availability
|
||||
}
|
||||
gateway.catalog.SetPricingStore(m.metadata)
|
||||
gateway.catalog.SetAvailabilityStore(availability)
|
||||
gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath))
|
||||
return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil
|
||||
return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}}, nil
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) start(runtime *gatewayRuntime) {
|
||||
@@ -264,6 +279,9 @@ func (m *RuntimeManager) Reload() (ApplyResult, error) {
|
||||
}
|
||||
|
||||
func (m *RuntimeManager) Shutdown() {
|
||||
if m.availabilityCancel != nil {
|
||||
m.availabilityCancel()
|
||||
}
|
||||
if current := m.current.Load(); current != nil {
|
||||
current.cancel()
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,9 @@ func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map
|
||||
// visible without dumping full payloads. Bodies stay out of attempt
|
||||
// records; the hub redactor scrubs configured secrets from log output.
|
||||
if len(errBody) > 0 {
|
||||
snippet := string(errBody)
|
||||
redactor := config.NewSecretRedactor()
|
||||
redactor.Replace(g.cfg)
|
||||
snippet := redactor.String(string(errBody))
|
||||
if len(snippet) > 240 {
|
||||
snippet = snippet[:240]
|
||||
}
|
||||
@@ -300,7 +302,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
}
|
||||
setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy)
|
||||
started := time.Now()
|
||||
resp, err := node.proxy.client.Do(req)
|
||||
resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
|
||||
duration := time.Since(started)
|
||||
if ctx.Err() != nil {
|
||||
// The parent budget expired while this attempt was in flight. Its
|
||||
@@ -576,7 +578,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
|
||||
return nil, err, 0
|
||||
}
|
||||
started := time.Now()
|
||||
resp, err := proxy.client.Do(req)
|
||||
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
|
||||
duration := time.Since(started)
|
||||
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration)
|
||||
if err != nil {
|
||||
@@ -645,7 +647,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
keyID := config.KeyDisplayID(node.key)
|
||||
setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy)
|
||||
attemptStarted := time.Now()
|
||||
resp, err := proxy.client.Do(req)
|
||||
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
|
||||
attemptDuration := time.Since(attemptStarted)
|
||||
if ctx.Err() != nil {
|
||||
// The request budget expired while this attempt was in flight. A
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const FreeModelCheckInterval = time.Hour
|
||||
const FailedModelCheckInterval = 24 * time.Hour
|
||||
|
||||
type Availability struct {
|
||||
Model string `json:"model"`
|
||||
Disabled bool `json:"disabled"`
|
||||
CheckedAt time.Time `json:"checked_at,omitempty"`
|
||||
NextCheck time.Time `json:"next_check"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
Generation uint64 `json:"-"`
|
||||
}
|
||||
|
||||
type AvailabilityStore struct {
|
||||
mu sync.RWMutex
|
||||
path string
|
||||
items map[string]Availability
|
||||
}
|
||||
|
||||
func NewAvailabilityStore(path string) (*AvailabilityStore, error) {
|
||||
s := &AvailabilityStore{path: path, items: map[string]Availability{}}
|
||||
if path != "" {
|
||||
b, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
if err = json.Unmarshal(b, &s.items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if s.items == nil {
|
||||
s.items = map[string]Availability{}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *AvailabilityStore) Get(model string) Availability {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
item := s.items[model]
|
||||
item.Model = model
|
||||
return item
|
||||
}
|
||||
|
||||
func (s *AvailabilityStore) Disabled(model string) bool { return s.Get(model).Disabled }
|
||||
|
||||
// A manual restore invalidates results from probes that were already running.
|
||||
func (s *AvailabilityStore) Restore(model string, now time.Time) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
item := s.items[model]
|
||||
previous, existed := s.items[model]
|
||||
item.Model, item.Disabled, item.Reason = model, false, "manually_enabled"
|
||||
item.NextCheck = now.Add(FreeModelCheckInterval)
|
||||
item.Generation++
|
||||
s.items[model] = item
|
||||
if err := s.saveLocked(); err != nil {
|
||||
if existed {
|
||||
s.items[model] = previous
|
||||
} else {
|
||||
delete(s.items, model)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
item := s.items[model]
|
||||
if item.Generation != generation {
|
||||
return nil
|
||||
}
|
||||
item.Model, item.Disabled = model, !success
|
||||
item.CheckedAt, item.Reason, item.Channel = now, reason, channel
|
||||
interval := FreeModelCheckInterval
|
||||
if !success {
|
||||
interval = FailedModelCheckInterval
|
||||
}
|
||||
item.NextCheck = now.Add(interval)
|
||||
s.items[model] = item
|
||||
return s.saveLocked()
|
||||
}
|
||||
|
||||
func (s *AvailabilityStore) saveLocked() error {
|
||||
if s.path == "" {
|
||||
return nil
|
||||
}
|
||||
b, err := json.MarshalIndent(s.items, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(filepath.Dir(s.path), ".availability-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
if _, err = f.Write(b); err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if closeErr := f.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(f.Name(), s.path)
|
||||
}
|
||||
@@ -61,6 +61,7 @@ type Catalog struct {
|
||||
updatedAt time.Time
|
||||
prefer config.Tier
|
||||
pricing *PricingStore
|
||||
availability *AvailabilityStore
|
||||
cachePath string
|
||||
cacheSource string
|
||||
stale bool
|
||||
@@ -97,6 +98,12 @@ func (c *Catalog) SetPricingStore(store *PricingStore) {
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Catalog) SetAvailabilityStore(store *AvailabilityStore) {
|
||||
c.mu.Lock()
|
||||
c.availability = store
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// MetadataSnapshot reports pricing freshness without exposing the store.
|
||||
func (c *Catalog) MetadataSnapshot() MetadataSnapshot {
|
||||
c.mu.RLock()
|
||||
@@ -197,6 +204,9 @@ func (c *Catalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool)
|
||||
}
|
||||
|
||||
func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) {
|
||||
if c.availability != nil && c.availability.Disabled(model) {
|
||||
return Route{}, fmt.Errorf("model %q is disabled after a failed availability check; restore it in the WebUI or wait for the next probe", model)
|
||||
}
|
||||
keyTiers := c.keyTierOrderLocked(model, hasZenKeys, hasGoKeys)
|
||||
// OpenCode's public credential is a Zen-only lane. Every free model starts
|
||||
// there, even if the current catalog only advertises it on Go: an upstream
|
||||
@@ -291,6 +301,9 @@ func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGo
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
if c.availability != nil && c.availability.Disabled(model) {
|
||||
return Route{}, fmt.Errorf("model %q is disabled after a failed availability check", model)
|
||||
}
|
||||
catalogPending := len(c.zen) == 0 && len(c.goModels) == 0
|
||||
advertised := c.zen[model]
|
||||
if tier == config.TierGo {
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
modelsDevDefaultURL = "https://models.dev/api.json"
|
||||
modelsDevDefaultURL = CapabilitiesURL
|
||||
modelsDevRefresh = 24 * time.Hour
|
||||
modelsDevTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
wire "opencode2api/internal/protocol"
|
||||
)
|
||||
|
||||
// models.dev publishes limits per provider. The primary OpenCode provider
|
||||
// must win for duplicated model IDs, and other OpenCode tiers must still
|
||||
// contribute the models they alone describe.
|
||||
func TestDecodeModelsDevKeepsLimitsAndMergesTiers(t *testing.T) {
|
||||
payload := []byte(`{
|
||||
"opencode": {"id":"opencode","models":{
|
||||
"shared":{"id":"shared","limit":{"context":1000,"output":100},"cost":{"input":1,"output":2}},
|
||||
"zen-only":{"id":"zen-only","limit":{"context":2000,"input":1500,"output":200}}
|
||||
}},
|
||||
"opencode-go": {"id":"opencode-go","models":{
|
||||
"shared":{"id":"shared","limit":{"context":9000,"output":900},"cost":{"input":1,"output":2}},
|
||||
"go-only":{"id":"go-only","limit":{"context":4000,"output":400},"cost":{"input":0,"output":0}}
|
||||
}},
|
||||
"anthropic":{"id":"anthropic","models":{"claude":{"id":"claude","limit":{"context":7}}}}
|
||||
}`)
|
||||
|
||||
models, err := decodeModelsDev(payload)
|
||||
if err != nil {
|
||||
t.Fatalf("decodeModelsDev: %v", err)
|
||||
}
|
||||
if _, exists := models["claude"]; exists {
|
||||
t.Fatal("non-OpenCode provider leaked into the metadata")
|
||||
}
|
||||
|
||||
shared := models["shared"]
|
||||
if shared.ContextWindow != 1000 || shared.MaxOutput != 100 {
|
||||
t.Errorf("shared = ctx %d/%d, want the primary provider limits 1000/100", shared.ContextWindow, shared.MaxOutput)
|
||||
}
|
||||
if shared.Input == nil || *shared.Input != 1 {
|
||||
t.Errorf("shared input cost = %v, want 1", shared.Input)
|
||||
}
|
||||
|
||||
zen := models["zen-only"]
|
||||
if zen.ContextWindow != 2000 || zen.MaxInput != 1500 || zen.MaxOutput != 200 {
|
||||
t.Errorf("zen-only = ctx %d, input %d, output %d; want 2000/1500/200", zen.ContextWindow, zen.MaxInput, zen.MaxOutput)
|
||||
}
|
||||
|
||||
goOnly, exists := models["go-only"]
|
||||
if !exists {
|
||||
t.Fatal("go-only model missing; tiers must be merged instead of the first provider winning alone")
|
||||
}
|
||||
if goOnly.ContextWindow != 4000 || goOnly.MaxOutput != 400 {
|
||||
t.Errorf("go-only = ctx %d/%d, want 4000/400", goOnly.ContextWindow, goOnly.MaxOutput)
|
||||
}
|
||||
if models["go-only"].Output == nil || *models["go-only"].Output != 0 {
|
||||
t.Errorf("go-only output cost = %v, want zero output cost preserved", models["go-only"].Output)
|
||||
}
|
||||
}
|
||||
|
||||
// OpenCode's capability catalog stays authoritative; models.dev only fills the
|
||||
// limits it omitted so discovery clients still get per-model numbers.
|
||||
func TestMetadataForTierFillsMissingLimitsFromModelsDev(t *testing.T) {
|
||||
catalog := NewCatalog(config.TierZen, nil)
|
||||
catalog.SetPricingStore(&PricingStore{models: map[string]Price{
|
||||
"alpha": {ID: "alpha", ContextWindow: 262144, MaxOutput: 32768},
|
||||
"beta": {ID: "beta", ContextWindow: 500000, MaxInput: 400000, MaxOutput: 64000},
|
||||
}})
|
||||
catalog.ReplaceWithCapabilities(
|
||||
[]string{"alpha", "beta"},
|
||||
nil,
|
||||
map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}},
|
||||
nil,
|
||||
map[config.Tier]map[string]Metadata{config.TierZen: {
|
||||
"alpha": {ContextWindow: 1000000, MaxOutput: 128000},
|
||||
"beta": {Reasoning: true},
|
||||
}},
|
||||
)
|
||||
|
||||
alpha := catalog.MetadataForTier("alpha", config.TierZen)
|
||||
if alpha.ContextWindow != 1000000 || alpha.MaxOutput != 128000 {
|
||||
t.Errorf("alpha = ctx %d/%d, want the catalog values 1000000/128000", alpha.ContextWindow, alpha.MaxOutput)
|
||||
}
|
||||
|
||||
beta := catalog.MetadataForTier("beta", config.TierZen)
|
||||
if beta.ContextWindow != 500000 || beta.MaxInput != 400000 || beta.MaxOutput != 64000 {
|
||||
t.Errorf("beta = ctx %d, input %d, output %d; want 500000/400000/64000", beta.ContextWindow, beta.MaxInput, beta.MaxOutput)
|
||||
}
|
||||
if !beta.Reasoning {
|
||||
t.Error("beta lost its catalog capability flags while limits were filled")
|
||||
}
|
||||
|
||||
if unknown := catalog.MetadataForTier("gamma", config.TierZen); unknown.ContextWindow != 0 {
|
||||
t.Errorf("gamma = ctx %d, want zero for a model no source describes", unknown.ContextWindow)
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user