mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
feat(diagnostics): pin a Playground request to one relay (#167)
Resolved against #170 so a relay pin clears the per-attempt WARP choice (attemptUseWARP). The relay list is now credential-redacted, and a pin may name a relay by its redacted URL.
This commit is contained in:
1 parent
46eb13ea03
commit
b296a61d0e
7 files changed
+235
-7
No files matched your search
+28
-5
@@ -31,9 +31,10 @@ type DebugKeySelection struct {
|
||||
// expressed in, which upstream key to test (Mode "auto" or "selected", the
|
||||
// latter naming Tier and ID), and the request body itself.
|
||||
type DebugInferenceRequest struct {
|
||||
Protocol protocol.Protocol `json:"protocol"`
|
||||
Key DebugKeySelection `json:"key,omitempty"`
|
||||
Request map[string]any `json:"request"`
|
||||
Protocol protocol.Protocol `json:"protocol"`
|
||||
Key DebugKeySelection `json:"key,omitempty"`
|
||||
Relay gateway.RelaySelection `json:"relay,omitempty"`
|
||||
Request map[string]any `json:"request"`
|
||||
}
|
||||
|
||||
// DebugInferenceResult is the outcome of a Playground request: the status and
|
||||
@@ -49,6 +50,7 @@ type DebugInferenceResult struct {
|
||||
Route modelcatalog.RouteDiagnostic `json:"route"`
|
||||
SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"`
|
||||
KeyTest string `json:"key_test,omitempty"`
|
||||
RelayTest string `json:"relay_test,omitempty"`
|
||||
Response any `json:"response"`
|
||||
}
|
||||
|
||||
@@ -59,11 +61,12 @@ func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) {
|
||||
models, metadata := a.manager.DebugModels()
|
||||
catalog := a.manager.Resources().Models
|
||||
keys := a.manager.DebugKeys()
|
||||
relays := a.manager.DebugRelays()
|
||||
a.mu.Lock()
|
||||
last := a.lastInference
|
||||
a.mu.Unlock()
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last})
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "relays": relays, "last_inference": last})
|
||||
}
|
||||
|
||||
// handleDebugInference runs a request through the gateway itself, in process
|
||||
@@ -112,6 +115,23 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !input.Relay.Empty() {
|
||||
known := false
|
||||
for index, name := range a.manager.DebugRelays() {
|
||||
if input.Relay.Index != nil && *input.Relay.Index != index {
|
||||
continue
|
||||
}
|
||||
if input.Relay.Name != "" && input.Relay.Name != name {
|
||||
continue
|
||||
}
|
||||
known = true
|
||||
break
|
||||
}
|
||||
if !known {
|
||||
writeAdminError(w, http.StatusBadRequest, "unknown_relay", "relay.index or relay.name does not match a configured relay")
|
||||
return
|
||||
}
|
||||
}
|
||||
route := a.manager.DebugRoute(model, input.Protocol)
|
||||
if selectedKey != nil {
|
||||
selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier)
|
||||
@@ -140,6 +160,9 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
|
||||
if !input.Relay.Empty() {
|
||||
request = request.WithContext(gateway.WithRelayOverride(request.Context(), input.Relay))
|
||||
}
|
||||
if selectedKey != nil {
|
||||
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
|
||||
}
|
||||
@@ -178,7 +201,7 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
|
||||
result := DebugInferenceResult{
|
||||
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
|
||||
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route,
|
||||
SelectedKey: selectedKey, KeyTest: keyTest, Response: raw,
|
||||
SelectedKey: selectedKey, KeyTest: keyTest, RelayTest: trace.Proxy, Response: raw,
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.lastInference = &result
|
||||
|
||||
@@ -104,6 +104,7 @@ type anonymousCursor struct {
|
||||
start int
|
||||
offset int
|
||||
used []bool
|
||||
single bool
|
||||
}
|
||||
|
||||
// anonymousPool builds one anonymous node per proxy transport, or an empty
|
||||
@@ -153,6 +154,24 @@ func (p *anonymousNodes) HasPool() bool {
|
||||
// CursorFor returns a cursor whose first node is stable for a non-empty
|
||||
// affinity key, keeping a conversation on one exit; an empty affinity rotates
|
||||
// the starting node round-robin.
|
||||
// CursorForProxy returns a cursor whose first Next hands back the node that
|
||||
// uses proxy and whose second returns nil, so a relay-pinned diagnostic
|
||||
// attempts exactly one exit. A proxy outside the pool yields the same
|
||||
// single-shot cursor over no node, which the caller reports as an error.
|
||||
func (p *anonymousNodes) CursorForProxy(proxy *proxyTransport) anonymousCursor {
|
||||
c := anonymousCursor{pool: p, offset: len(p.nodes), single: true}
|
||||
if p == nil || proxy == nil {
|
||||
return c
|
||||
}
|
||||
for i, node := range p.nodes {
|
||||
if node.proxy == proxy {
|
||||
c.start = i
|
||||
return c
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor {
|
||||
if p == nil || len(p.nodes) == 0 {
|
||||
return anonymousCursor{pool: p}
|
||||
@@ -302,6 +321,15 @@ func (c *anonymousCursor) Next() *anonymousNode {
|
||||
if c.used == nil {
|
||||
c.used = make([]bool, n)
|
||||
}
|
||||
if c.single {
|
||||
index := c.start
|
||||
c.single = false
|
||||
c.offset = n
|
||||
if index < 0 || index >= n {
|
||||
return nil
|
||||
}
|
||||
return c.pool.nodes[index]
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
isBlocked := func(node *anonymousNode) bool {
|
||||
return node.proxy != nil && node.proxy.blockedUntil.Load() > now
|
||||
|
||||
@@ -586,6 +586,15 @@ type DebugKeyView struct {
|
||||
CooldownUntil *time.Time `json:"cooldown_until,omitempty"`
|
||||
}
|
||||
|
||||
// DebugRelays lists the anonymous relays in pool order for the Playground.
|
||||
func (m *RuntimeController) DebugRelays() []string {
|
||||
rt := m.current.Load()
|
||||
if rt == nil || rt.gateway == nil {
|
||||
return nil
|
||||
}
|
||||
return rt.gateway.RelayNames()
|
||||
}
|
||||
|
||||
// DebugKeys lists every configured upstream key per tier so the Playground can
|
||||
// offer an explicit per-key test target.
|
||||
func (m *RuntimeController) DebugKeys() map[string][]DebugKeyView {
|
||||
|
||||
@@ -59,6 +59,87 @@ func WithDebugKeyOverride(ctx context.Context, override DebugKeyOverride) contex
|
||||
return context.WithValue(WithDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override)
|
||||
}
|
||||
|
||||
// RelaySelection names one configured upstream relay (proxy) so a diagnostic
|
||||
// request can be pinned to it. Index is the position in the configured proxy
|
||||
// list, Name is the proxy URL; supplying both requires them to agree. Either
|
||||
// alone is enough, and an empty selection means normal routing.
|
||||
type RelaySelection struct {
|
||||
Index *int `json:"index,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// Empty reports whether the selection names no relay.
|
||||
func (r RelaySelection) Empty() bool {
|
||||
return r.Index == nil && r.Name == ""
|
||||
}
|
||||
|
||||
type relayOverrideContextKey struct{}
|
||||
|
||||
// WithRelayOverride pins one inference request to a single configured relay,
|
||||
// on every tier: the anonymous lane walks exactly that exit and a key request
|
||||
// is sent through that proxy, each with a single attempt and no failover.
|
||||
// Session minting, system prompt, tool shaping and the transport stay the
|
||||
// production path. The request is marked diagnostic, so the pinned attempt
|
||||
// changes no cooldown, proxy health or IP-block state and cannot poison the
|
||||
// relays it is meant to measure.
|
||||
func WithRelayOverride(ctx context.Context, selection RelaySelection) context.Context {
|
||||
return context.WithValue(WithDiagnosticRequest(ctx), relayOverrideContextKey{}, selection)
|
||||
}
|
||||
|
||||
func relayOverrideFrom(ctx context.Context) (RelaySelection, bool) {
|
||||
selection, ok := ctx.Value(relayOverrideContextKey{}).(RelaySelection)
|
||||
if !ok || selection.Empty() {
|
||||
return RelaySelection{}, false
|
||||
}
|
||||
return selection, true
|
||||
}
|
||||
|
||||
// RelayNames lists the configured relays in configuration order, with any
|
||||
// credentials redacted, so a caller can name one by index or by URL.
|
||||
func (g *Gateway) RelayNames() []string {
|
||||
if g.transports == nil {
|
||||
return nil
|
||||
}
|
||||
names := make([]string, 0, len(g.transports.items))
|
||||
for _, transport := range g.transports.items {
|
||||
if transport != nil {
|
||||
names = append(names, config.RedactURL(transport.name))
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// RelayProxy resolves a selection against the configured proxies. It reports
|
||||
// false when nothing matches, so a typo surfaces as an error instead of a
|
||||
// silent fallback to normal routing.
|
||||
func (g *Gateway) RelayProxy(selection RelaySelection) (*proxyTransport, bool) {
|
||||
if g.transports == nil {
|
||||
return nil, false
|
||||
}
|
||||
index := -1
|
||||
if selection.Index != nil {
|
||||
index = *selection.Index
|
||||
if index < 0 || index >= len(g.transports.items) {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
for i, transport := range g.transports.items {
|
||||
if transport == nil {
|
||||
continue
|
||||
}
|
||||
if index >= 0 && i != index {
|
||||
continue
|
||||
}
|
||||
if selection.Name != "" && transport.name != selection.Name && config.RedactURL(transport.name) != selection.Name {
|
||||
continue
|
||||
}
|
||||
return transport, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var errRelayNotFound = errors.New("relay does not match any configured proxy")
|
||||
|
||||
func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) {
|
||||
override, ok := ctx.Value(debugKeyOverrideContextKey{}).(DebugKeyOverride)
|
||||
return override, ok && override.KeyID != ""
|
||||
@@ -380,6 +461,18 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
|
||||
limit = g.cfg.Retry.MaxAttempts
|
||||
}
|
||||
// A relay-pinned diagnostic sends exactly one attempt through the chosen
|
||||
// exit, so the answer describes that relay alone. An unresolvable relay is
|
||||
// an error rather than a silent fallback, because a typo would otherwise
|
||||
// read as a relay verdict.
|
||||
if selection, ok := relayOverrideFrom(ctx); ok {
|
||||
proxy, found := g.RelayProxy(selection)
|
||||
if !found {
|
||||
return nil, errRelayNotFound, 0
|
||||
}
|
||||
cursor = g.anonymous.CursorForProxy(proxy)
|
||||
limit = 1
|
||||
}
|
||||
proxies := 0
|
||||
attempts := 0
|
||||
rawBody := bodies[config.TierZen]
|
||||
@@ -844,6 +937,9 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
|
||||
setRequestShape(ctx, changed, toolRenames)
|
||||
useWARP := !node.bound && g.usesWARP(route.ID, override.Tier, false)
|
||||
proxy := nodes.Proxy(node)
|
||||
if pinned, ok := g.relayPin(ctx, proxy); ok {
|
||||
proxy, useWARP = pinned, false
|
||||
}
|
||||
if !useWARP {
|
||||
if proxy == nil {
|
||||
return nil, errors.New("selected upstream key has no proxy binding"), 0
|
||||
@@ -924,7 +1020,13 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
}
|
||||
setRequestShape(ctx, changed, toolRenames)
|
||||
useWARP := g.usesWARP(route.ID, route.Tier, false)
|
||||
for attempts < g.cfg.Retry.MaxAttempts {
|
||||
// A relay-pinned diagnostic gets exactly one attempt: rotating keys would
|
||||
// no longer describe the relay that was asked for.
|
||||
attemptLimit := g.cfg.Retry.MaxAttempts
|
||||
if _, pinned := relayOverrideFrom(ctx); pinned {
|
||||
attemptLimit = 1
|
||||
}
|
||||
for attempts < attemptLimit {
|
||||
if ctx.Err() != nil {
|
||||
// Same guard as the anonymous loop: an exhausted request budget
|
||||
// must not be spent rotating keys that were never really tried.
|
||||
@@ -954,6 +1056,11 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
return nil, err, attempts
|
||||
}
|
||||
proxy := nodes.Proxy(node)
|
||||
// A relay pin replaces the proxy the key is bound to, so a pinned
|
||||
// diagnostic measures that relay alone.
|
||||
if pinned, ok := g.relayPin(ctx, proxy); ok {
|
||||
proxy, attemptUseWARP = pinned, false
|
||||
}
|
||||
if !attemptUseWARP {
|
||||
if proxy == nil {
|
||||
lastErr = errors.New("upstream key has no proxy binding")
|
||||
@@ -1148,6 +1255,9 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
|
||||
leg += strconv.Itoa(status)
|
||||
}
|
||||
leg += ":" + strconv.FormatInt(max(duration.Milliseconds(), 0), 10) + "ms"
|
||||
if anonymous && proxy != nil {
|
||||
leg += "@" + config.RedactURL(proxy.name)
|
||||
}
|
||||
meta.Legs = append(meta.Legs, leg)
|
||||
}
|
||||
if g.monitor == nil {
|
||||
@@ -1487,3 +1597,17 @@ func projectID(project string) string {
|
||||
func isNonRetryableClientResponse(resp *http.Response, err error) bool {
|
||||
return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests
|
||||
}
|
||||
|
||||
// relayPin returns the proxy a relay-pinned diagnostic names, and whether a
|
||||
// pin applied. An unresolvable pin keeps the request on its normal proxy: the
|
||||
// admin endpoint validates the selection before it reaches here.
|
||||
func (g *Gateway) relayPin(ctx context.Context, current *proxyTransport) (*proxyTransport, bool) {
|
||||
selection, ok := relayOverrideFrom(ctx)
|
||||
if !ok {
|
||||
return current, false
|
||||
}
|
||||
if pinned, found := g.RelayProxy(selection); found {
|
||||
return pinned, true
|
||||
}
|
||||
return current, false
|
||||
}
|
||||
Reference in new issue
Block a user