diff --git a/README.md b/README.md index e524255..2cf2690 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,8 @@ OAuth routes follow separate rules: the selected OAuth tier owns the request, us Mark a provider-managed rotating endpoint with `pool+https://proxy.example:8443` or `https://proxy.example:8443#pool`. Each attempt then opens a fresh connection without keep-alive/HTTP/2 reuse; these entries do not use static-node cooldown or health eviction. The provider must actually rotate its exits. Static proxies retain connection reuse, health tracking, and key bindings. `proxy_bindings` can pin a key fingerprint to a configured proxy. +`keys_direct: true` pins unbound manual Zen/Go keys to dual-stack `direct`, including model discovery and active probes, without failover to proxies or WARP. Explicit `proxy_bindings` take priority, including `direct4`/`direct6` bindings. The default is `false`. If needed, a key-only direct transport is created at runtime without changing `proxies` or copying `proxyfile` entries into the saved file. This injected route is never added to anonymous or automatic OAuth routing; explicitly configured direct routes remain available to them. OAuth connections retain their own routing policy. This setting does not disable anonymous-first routing for free models; disable `anonymous` separately if all inference must use keys. + To choose a direct address family per upstream key, first include the routes in `proxies` or `proxyfile`, then bind the key fingerprints: ```json diff --git a/config.example.json b/config.example.json index ed5fc20..731221b 100644 --- a/config.example.json +++ b/config.example.json @@ -5,6 +5,7 @@ "go_keys": [], // Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key. "anonymous": false, + "keys_direct": false, "warp": { "enabled": false, "pool_size": 2, diff --git a/docs/management.md b/docs/management.md index b6b16f7..39a4ff6 100644 --- a/docs/management.md +++ b/docs/management.md @@ -78,6 +78,7 @@ Common management defaults: | `logging.ring_size` | `2000`; range 100–50,000. | | `logging.dump_request_bodies` | `false`; also requires debug logging, capped at 64 KiB per prepared body. | | `models.active_probes` | `false`; real traffic supplies default availability observations. | +| `keys_direct` | `false`; pins unbound manual Zen/Go keys to dual-stack direct egress; explicit bindings win. Anonymous/OAuth routing is unchanged. | ## Go OAuth and Zen PAYG OAuth diff --git a/internal/admin/server.go b/internal/admin/server.go index 6cbf4e2..c11e38e 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -160,6 +160,7 @@ type ConfigView struct { ZenKeys []SecretView `json:"zen_keys"` GoKeys []SecretView `json:"go_keys"` Anonymous bool `json:"anonymous"` + KeysDirect bool `json:"keys_direct"` Warp config.WarpConfig `json:"warp"` Proxies []SecretView `json:"proxies"` ProxyFile string `json:"proxyfile"` @@ -209,6 +210,7 @@ type ConfigUpdate struct { ZenKeys []SecretInput `json:"zen_keys"` GoKeys []SecretInput `json:"go_keys"` Anonymous bool `json:"anonymous"` + KeysDirect *bool `json:"keys_direct,omitempty"` Warp config.WarpConfig `json:"warp"` Proxies []SecretInput `json:"proxies"` ProxyFile string `json:"proxyfile"` @@ -277,6 +279,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { ZenOAuth: current.ZenOAuth, Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, ProxyBindings: proxyBindings, + KeysDirect: current.KeysDirect, Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, @@ -289,6 +292,10 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { candidate.ZenOAuth = latest.ZenOAuth candidate.ServerKeyMetadata = latest.ServerKeyMetadata candidate.Rotation = latest.Rotation + candidate.KeysDirect = latest.KeysDirect + if update.KeysDirect != nil { + candidate.KeysDirect = *update.KeysDirect + } candidate.WebUI.Username = latest.WebUI.Username candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash if update.Reasoning == nil { @@ -459,7 +466,7 @@ func (a *Server) configView() ConfigView { upstream.Anonymous = config.RedactURL(upstream.Anonymous) return ConfigView{ Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, Warp: cfg.Warp, - Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: proxyBindings, Upstream: upstream, Retry: cfg.Retry, Models: cfg.Models, + Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: proxyBindings, KeysDirect: cfg.KeysDirect, Upstream: upstream, Retry: cfg.Retry, Models: cfg.Models, Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning, WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes}, Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled}, diff --git a/internal/config/config.go b/internal/config/config.go index 49cbb28..95e10af 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -37,6 +37,7 @@ type Config struct { GoOAuth *oauth.Connection `json:"go_oauth,omitempty"` ZenOAuth *oauth.Connection `json:"zen_oauth,omitempty"` Anonymous bool `json:"anonymous"` + KeysDirect bool `json:"keys_direct"` Warp WarpConfig `json:"warp"` Proxies []string `json:"proxies"` ProxyFile string `json:"proxyfile"` diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 24bb311..48a3794 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -117,16 +117,35 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war if err != nil { return nil, err } - transports, err := transportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) + proxyNames := append([]string(nil), cfg.RuntimeProxies()...) + injectedDirect := false + hasManualKeys := cfg.ZenOAuth == nil && len(cfg.ZenKeys) > 0 || cfg.GoOAuth == nil && len(cfg.GoKeys) > 0 + if cfg.KeysDirect && hasManualKeys { + hasDirect := false + for _, name := range proxyNames { + if name == "direct" { + hasDirect = true + break + } + } + if !hasDirect { + proxyNames = append(proxyNames, "direct") + injectedDirect = true + } + } + transports, err := transportPool(proxyNames, cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) if err != nil { return nil, err } + if injectedDirect { + transports.items[len(transports.items)-1].keysOnly = true + } cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second zenKeys := cfg.ZenKeys if cfg.ZenOAuth != nil { zenKeys = nil } - zenNodes, err := nodePool(zenKeys, transports, cooldown, cfg.ProxyBindings) + zenNodes, err := nodePool(zenKeys, transports, cooldown, cfg.ProxyBindings, cfg.KeysDirect) if err != nil { return nil, fmt.Errorf("zen node pool: %w", err) } @@ -134,7 +153,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war if cfg.GoOAuth != nil { goKeys = nil } - goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings) + goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings, cfg.KeysDirect) if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 98e0667..57fca7c 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -70,6 +70,12 @@ type healthWarp struct { func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { _, models := g.availableModels() proxyTotal, proxyHealthy := g.transports.healthCounts() + sharedHealthy := proxyHealthy + for _, proxy := range g.transports.items { + if proxy.keysOnly && proxy.healthy.Load() { + sharedHealthy-- + } + } zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len() if g.cfg.ZenOAuth != nil { zenKeys = 1 @@ -130,6 +136,11 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { // Proxies carry Go-tier traffic whenever Go keys exist, and every lane // while WARP is off; free-model traffic alone does not need them. proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0 || g.cfg.ZenOAuth != nil) + sharedRequired := g.cfg.GoOAuth != nil || g.cfg.ZenOAuth != nil || g.cfg.Anonymous && g.warp == nil + if sharedRequired && sharedHealthy == 0 { + proxyBlocking = true + issues = append(issues, "no_healthy_shared_proxies") + } if proxyHealthy == 0 { issues = append(issues, "no_healthy_proxies") } diff --git a/internal/gateway/oauth.go b/internal/gateway/oauth.go index 0f72186..cbdeeeb 100644 --- a/internal/gateway/oauth.go +++ b/internal/gateway/oauth.go @@ -207,10 +207,19 @@ func (g *Gateway) oauthProxy(ctx context.Context, connection *oauth.Connection, if pinned != nil { return pinned, nil } + proxies := make([]*proxyTransport, 0, len(g.transports.items)) + for _, proxy := range g.transports.items { + if proxy != nil && !proxy.keysOnly { + proxies = append(proxies, proxy) + } + } + if len(proxies) == 0 { + return nil, errProxyUnavailable + } digest := sha256.Sum256([]byte(oauthAccountID(connection) + "\x00" + affinity)) - start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(g.transports.items))) - for step := range len(g.transports.items) { - proxy := g.transports.items[(start+offset+step)%len(g.transports.items)] + start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(proxies))) + for step := range len(proxies) { + proxy := proxies[(start+offset+step)%len(proxies)] if proxy != nil && proxy.healthy.Load() { return proxy, nil } diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index b64d3e3..ae726eb 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -33,6 +33,7 @@ type proxyTransport struct { index int name string pool bool + keysOnly bool client *http.Client bun *http.Client healthy atomic.Bool @@ -116,6 +117,9 @@ func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Dura } pool.nodes = make([]*anonymousNode, 0, len(transports.items)) for _, proxy := range transports.items { + if proxy.keysOnly { + continue + } if proxy.pool { pool.hasPool = true } @@ -684,7 +688,7 @@ type upstreamNodes struct { // configured, bound keys are permanently pinned to their specified proxy and // fail closed if that proxy fails. Unbound keys are distributed in round-robin // order and can fail over to other proxies. -func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration, bindings map[string]string) (*upstreamNodes, error) { +func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration, bindings map[string]string, keysDirect bool) (*upstreamNodes, error) { if transports == nil || len(transports.items) == 0 { return nil, fmt.Errorf("at least one proxy transport is required") } @@ -710,6 +714,9 @@ func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration if !hasBinding { targetProxy, hasBinding = bindings[key] } + if !hasBinding && keysDirect { + targetProxy, hasBinding = "direct", true + } var proxyIndex int var bound bool diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index bac5611..aa9822d 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -149,7 +149,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult } cursor := g.zenNodes.CursorFor(ids.Session) if node := cursor.Next(); node != nil { - if g.usesWARP(model, config.TierZen, false) { + if !node.bound && g.usesWARP(model, config.TierZen, false) { lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, warp: true}) } else if proxy := g.zenNodes.Proxy(node); proxy != nil { lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, client: g.inferenceClient(proxy, g.cfg.Upstream.Zen, model)}) diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index 3e284e5..61f1354 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -251,7 +251,7 @@ func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog } var lastErr error for _, proxy := range g.transports.items { - if proxy == nil || !proxy.healthy.Load() { + if proxy == nil || proxy.keysOnly || !proxy.healthy.Load() { continue } capabilities, err := modelcatalog.FetchCapabilities(ctx, proxy.client, modelcatalog.CapabilitiesURL) diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 7d31e24..4dfa7f7 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -110,7 +110,7 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, } clients := make([]*http.Client, 0, len(runtime.gateway.transports.items)) for _, proxy := range runtime.gateway.transports.items { - if proxy != nil && proxy.healthy.Load() { + if proxy != nil && !proxy.keysOnly && proxy.healthy.Load() { clients = append(clients, proxy.client) } } @@ -585,7 +585,7 @@ func (m *RuntimeController) Resources() ResourceSnapshot { goBindings := append([]int(nil), gateway.goNodes.bindingCount...) gateway.goNodes.bindingsMu.Unlock() for _, proxy := range gateway.transports.items { - status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous} + status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous && !proxy.keysOnly} if proxy.index < len(zenBindings) { status.ZenKeys = zenBindings[proxy.index] } diff --git a/webui/index.html b/webui/index.html index aaf641b..4dae7d8 100644 --- a/webui/index.html +++ b/webui/index.html @@ -887,6 +887,12 @@
匿名通道默认关闭,可能已被上游重点封堵。建议优先配置 Zen API Key;启用匿名不保证可用,也不会自动修改当前设置。
+