fix(admin): show aliases, guard the provider filter, tolerate failing upstreams (#23)

* fix(admin): attach model aliases to the model their target resolves to

The catalog grouped aliases by the raw target string and looked them up by
canonical provider/model id. A bare target never matched, so no model card
listed its aliases. Each alias now keys on the canonical id that the
registry resolves its target to. The alias view gains an additive
resolvedTarget field.

Model-id cells in the overview, usage and panels now show an alias badge
with the target, using the catalog alias list.

* fix(webui): omit the provider filter select until providers load

* fix(discovery): tolerate failing modelBaseUrls upstreams

A modelBaseUrls upstream that fails /v1/models must not fail the provider.
Discovery now fails only when baseUrl fails. The explicit models of the
failing upstream stay listed, and the other upstreams still merge.

The admin overview reports each failed upstream in the additive
upstreamErrors field. The registry logs it at most once per 10 minutes
per provider. The README states the new semantics.

* chore(webui): regenerate admin assets

Rebuilt with make admin-ui for the alias badge and the provider filter changes.

* style(auth): order authStore fields for fieldalignment

golangci-lint's fieldalignment check reported 240 leading pointer bytes on authStore where 232 is optimal. The bool anonymousAnyKey moves next to the mutexes. No behaviour change.
This commit is contained in:
2026-11-28 02:13:22 +00:00
committed by GitHub
parent 7fade3cdee
commit bfdffc2ab0
19 changed files with 493 additions and 103 deletions
+6 -3
View File
@@ -2401,9 +2401,12 @@ providers:
`modelBaseUrls` read the body for this purpose. `modelBaseUrls` read the body for this purpose.
- **Discovery and `metadataPath`** query `baseUrl` and every distinct - **Discovery and `metadataPath`** query `baseUrl` and every distinct
`modelBaseUrls` upstream, one request per upstream. An id is taken only from `modelBaseUrls` upstream, one request per upstream. An id is taken only from
the upstream its requests route to. Discovery fails as a whole when any the upstream its requests route to. Discovery fails as a whole only when `baseUrl`
upstream fails, keeping the last-known set; metadata keeps the ids of the fails, keeping the last-known set. A failing `modelBaseUrls` upstream does not
upstreams that answered. `modelBaseUrls` ids stay declared models. degrade the provider: its explicit `models` stay served, the other upstreams'
ids still merge, and the admin overview lists it under `upstreamErrors` (also
logged, at most once per 10 minutes). Metadata keeps the ids of the upstreams
that answered. `modelBaseUrls` ids stay declared models.
- **Admin catalog**: each `pathBaseUrls` key appears as a pseudo-model row - **Admin catalog**: each `pathBaseUrls` key appears as a pseudo-model row
(`gx10/v1/decide`). It is display only and never routable as a model. (`gx10/v1/decide`). It is display only and never routable as a model.
`kinds` labels a model id or a path key. The Models page then groups the `kinds` labels a model id or a path key. The Models page then groups the
+31 -3
View File
@@ -336,6 +336,26 @@ func replaceURLForm(msg, form string) string {
// base URL names no credential by itself, and any credential-shaped // base URL names no credential by itself, and any credential-shaped
// userinfo/query an operator mistakenly embedded in it is stripped by // userinfo/query an operator mistakenly embedded in it is stripped by
// sanitizeBaseURL before this view is ever built. // sanitizeBaseURL before this view is ever built.
// adminUpstreamErrorView is one tolerated modelBaseUrls discovery failure.
type adminUpstreamErrorView struct {
Upstream string `json:"upstream"`
Error string `json:"error"`
}
func adminUpstreamErrors(fails []upstreamFailure, rawBaseURL string) []adminUpstreamErrorView {
if len(fails) == 0 {
return nil
}
out := make([]adminUpstreamErrorView, len(fails))
for i, f := range fails {
out[i] = adminUpstreamErrorView{
Upstream: sanitizeBaseURL(f.Upstream),
Error: sanitizeProviderErr(sanitizeProviderErr(f.Err, f.Upstream), rawBaseURL),
}
}
return out
}
type adminProviderView struct { type adminProviderView struct {
LastRefresh time.Time `json:"lastRefresh"` LastRefresh time.Time `json:"lastRefresh"`
// OpenUntil is when this provider's breaker will next attempt a // OpenUntil is when this provider's breaker will next attempt a
@@ -394,6 +414,8 @@ type adminProviderView struct {
Type string `json:"type"` Type string `json:"type"`
BaseURL string `json:"baseUrl"` BaseURL string `json:"baseUrl"`
LastErr string `json:"lastErr,omitempty"` LastErr string `json:"lastErr,omitempty"`
// UpstreamErrors lists modelBaseUrls upstreams whose discovery failed while the provider stayed healthy.
UpstreamErrors []adminUpstreamErrorView `json:"upstreamErrors,omitempty"`
// HealthState is this provider's discovery circuit breaker state // HealthState is this provider's discovery circuit breaker state
// (feat/provider-health): "closed" (normal), "open" (backing off // (feat/provider-health): "closed" (normal), "open" (backing off
// after repeated discovery failures — maybeRefresh skips it until // after repeated discovery failures — maybeRefresh skips it until
@@ -649,6 +671,9 @@ type adminAliasView struct {
ModelMeta adminModelMetaView `json:"modelMeta"` ModelMeta adminModelMetaView `json:"modelMeta"`
Alias string `json:"alias"` Alias string `json:"alias"`
Target string `json:"target"` Target string `json:"target"`
// ResolvedTarget is Target's canonical "provider/model" id; omitted
// while Target resolves to no known model.
ResolvedTarget string `json:"resolvedTarget,omitempty"`
} }
// adminOverviewResponse is the full body of GET /admin/api/overview (spec // adminOverviewResponse is the full body of GET /admin/api/overview (spec
@@ -837,6 +862,7 @@ func (g *Gateway) buildAdminOverview() adminOverviewResponse {
ModelCount: s.modelCount, ModelCount: s.modelCount,
LastRefresh: s.lastRefresh, LastRefresh: s.lastRefresh,
LastErr: sanitizeProviderErr(s.lastErr, s.baseURL), LastErr: sanitizeProviderErr(s.lastErr, s.baseURL),
UpstreamErrors: adminUpstreamErrors(s.upstreamErrs, s.baseURL),
DiscoveryEnabled: s.discoveryEnabled, DiscoveryEnabled: s.discoveryEnabled,
HealthState: s.health.String(), HealthState: s.health.String(),
OpenUntil: s.openUntil, OpenUntil: s.openUntil,
@@ -908,10 +934,12 @@ func (g *Gateway) buildAdminAliasViews() []adminAliasView {
aliasSnaps := g.registry.aliasSnapshot() aliasSnaps := g.registry.aliasSnapshot()
aliases := make([]adminAliasView, len(aliasSnaps)) aliases := make([]adminAliasView, len(aliasSnaps))
for i, a := range aliasSnaps { for i, a := range aliasSnaps {
resolved, _ := g.registry.aliasTargetCanonical(a.Target)
aliases[i] = adminAliasView{ aliases[i] = adminAliasView{
Alias: a.Alias, Alias: a.Alias,
Target: a.Target, Target: a.Target,
ModelMeta: buildAdminModelMetaView(g.registry.resolveMetaForAliasName(a.Alias)), ResolvedTarget: resolved,
ModelMeta: buildAdminModelMetaView(g.registry.resolveMetaForAliasName(a.Alias)),
} }
} }
return aliases return aliases
+48 -48
View File
File diff suppressed because one or more lines are too long
+10 -8
View File
@@ -97,14 +97,16 @@ type adminCatalogResponse struct {
func (g *Gateway) buildAdminCatalog() adminCatalogResponse { func (g *Gateway) buildAdminCatalog() adminCatalogResponse {
snaps := g.registry.snapshot() snaps := g.registry.snapshot()
// aliasesByTarget groups every configured alias by its configured // aliasesByTarget groups every alias by the canonical id its target
// Target string (ModelAliases' own doc comment, llmgateway.go: a // resolves to (a target may be bare or provider-prefixed), so each
// target names a canonical "provider/model" id), so each model's own // model's own Aliases field below is a single map lookup. An alias
// Aliases field below is a single map lookup rather than a full scan // whose target resolves to no known model attaches to no model.
// of the alias list per model. aliasViews := g.buildAdminAliasViews()
aliasesByTarget := make(map[string][]string) aliasesByTarget := make(map[string][]string)
for _, a := range g.registry.aliasSnapshot() { for _, a := range aliasViews {
aliasesByTarget[a.Target] = append(aliasesByTarget[a.Target], a.Alias) if a.ResolvedTarget != "" {
aliasesByTarget[a.ResolvedTarget] = append(aliasesByTarget[a.ResolvedTarget], a.Alias)
}
} }
routers := g.buildAdminRouterViews() routers := g.buildAdminRouterViews()
@@ -181,7 +183,7 @@ func (g *Gateway) buildAdminCatalog() adminCatalogResponse {
} }
} }
return adminCatalogResponse{Providers: providers, Aliases: g.buildAdminAliasViews(), Routers: routers} return adminCatalogResponse{Providers: providers, Aliases: aliasViews, Routers: routers}
} }
// sortedKeys returns m's keys in ascending order, nil for an empty map. // sortedKeys returns m's keys in ascending order, nil for an empty map.
+49
View File
@@ -169,6 +169,55 @@ func TestAdminCatalog_AliasesGroupedByTarget(t *testing.T) {
} }
} }
// TestAdminCatalog_AliasTargetForms pins that a bare target, a
// provider-prefixed target and an unresolvable target behave as the
// registry's own resolution does: the first two attach to the canonical
// model, the last attaches nowhere but still lists in catalog.aliases.
func TestAdminCatalog_AliasTargetForms(t *testing.T) {
t.Parallel()
cfg := newAdminTestConfig()
cfg.ModelAliases = map[string]string{
"fast-bare": "z-model",
"fast-prefixed": "zeta/z-model",
"fast-missing": "no-such-model",
}
h, _ := newAdminGatewayHandle(t, cfg)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminCatalogPath, "sk-admin1"))
var got adminCatalogResponse
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v", err)
}
attached := map[string][]string{}
for _, p := range got.Providers {
for _, m := range p.Models {
attached[m.ID] = m.Aliases
}
}
want := []string{"fast-bare", "fast-prefixed"}
if g := attached["zeta/z-model"]; len(g) != 2 || g[0] != want[0] || g[1] != want[1] {
t.Errorf("zeta/z-model Aliases = %v, want %v", g, want)
}
for id, names := range attached {
for _, n := range names {
if n == "fast-missing" {
t.Errorf("unresolvable entry attached to %s", id)
}
}
}
resolved := map[string]string{}
for _, a := range got.Aliases {
resolved[a.Alias] = a.ResolvedTarget
}
if len(resolved) != 3 {
t.Fatalf("top-level Aliases = %v, want 3 entries", resolved)
}
if resolved["fast-bare"] != "zeta/z-model" || resolved["fast-prefixed"] != "zeta/z-model" || resolved["fast-missing"] != "" {
t.Errorf("ResolvedTarget = %v", resolved)
}
}
// --- GET /admin/api/consumers --- // --- GET /admin/api/consumers ---
func TestAdminConsumers_GateMatrix(t *testing.T) { func TestAdminConsumers_GateMatrix(t *testing.T) {
+2 -2
View File
@@ -325,8 +325,8 @@ func TestAdminOverview_SortedShapeAndVersion(t *testing.T) {
} }
wantAliases := []adminAliasView{ wantAliases := []adminAliasView{
{Alias: "aaliased/y", Target: "alpha/a-model-1"}, {Alias: "aaliased/y", Target: "alpha/a-model-1", ResolvedTarget: "alpha/a-model-1"},
{Alias: "zaliased/x", Target: "z-model"}, {Alias: "zaliased/x", Target: "z-model", ResolvedTarget: "zeta/z-model"},
} }
if len(got.Aliases) != len(wantAliases) { if len(got.Aliases) != len(wantAliases) {
t.Fatalf("aliases = %+v, want exactly %+v", got.Aliases, wantAliases) t.Fatalf("aliases = %+v, want exactly %+v", got.Aliases, wantAliases)
+6 -6
View File
@@ -731,16 +731,16 @@ type authStore struct {
inline map[[32]byte]*authEntry inline map[[32]byte]*authEntry
// anonymous is the principal for keyless requests; nil unless // anonymous is the principal for keyless requests; nil unless
// UsersConfig.AnonymousGroup is set. // UsersConfig.AnonymousGroup is set.
anonymous *authEntry anonymous *authEntry
// anonymousAnyKey admits an unknown key as anonymous instead of 401.
anonymousAnyKey bool
lastReloadErrMsg string lastReloadErrMsg string
failureLog logGate failureLog logGate
throttleLog logGate throttleLog logGate
fileUserCount int fileUserCount int
mu sync.RWMutex // anonymousAnyKey admits an unknown key as anonymous instead of 401.
buildMu sync.Mutex anonymousAnyKey bool
reloadMu sync.Mutex mu sync.RWMutex
buildMu sync.Mutex
reloadMu sync.Mutex
} }
// newAuthStore builds an authStore from cfg's groups and inline users. It // newAuthStore builds an authStore from cfg's groups and inline users. It
+44 -6
View File
@@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"sort" "sort"
"strings" "strings"
"sync"
"time" "time"
) )
@@ -36,6 +37,8 @@ type openaiAdapter struct {
// newOpenAIAdapter call site (every test, and any caller that never // newOpenAIAdapter call site (every test, and any caller that never
// sets this) keeps behaving exactly as before this feature existed. // sets this) keeps behaving exactly as before this feature existed.
metadataPath string metadataPath string
// upstreamErrs is the modelBaseUrls failures of the latest listModels call; guarded by upstreamMu.
upstreamErrs []upstreamFailure
// timeout is this adapter's resolved per-request timeout // timeout is this adapter's resolved per-request timeout
// (resolveProviderTimeout, timeout.go) — UNLIKE retry above, it is NOT // (resolveProviderTimeout, timeout.go) — UNLIKE retry above, it is NOT
// left at its zero value by a bare newOpenAIAdapter call: a // left at its zero value by a bare newOpenAIAdapter call: a
@@ -45,7 +48,8 @@ type openaiAdapter struct {
// sets it to defaultRequestTimeout; buildAdapters (providers.go) // sets it to defaultRequestTimeout; buildAdapters (providers.go)
// overwrites it with the real, config-resolved value for production // overwrites it with the real, config-resolved value for production
// use, the same way it overwrites retry/metadataPath above. // use, the same way it overwrites retry/metadataPath above.
timeout time.Duration timeout time.Duration
upstreamMu sync.Mutex
} }
// newOpenAIAdapter returns an openaiAdapter for provider name, with base as // newOpenAIAdapter returns an openaiAdapter for provider name, with base as
@@ -441,18 +445,51 @@ type modelsPayload struct {
} `json:"data"` } `json:"data"`
} }
// upstreamFailure is one modelBaseUrls upstream that failed discovery.
type upstreamFailure struct {
Upstream string
Err string
}
// upstreamErrorReporter is implemented by adapters whose discovery tolerates
// a failing secondary upstream and reports it out of band.
type upstreamErrorReporter interface {
upstreamErrors() []upstreamFailure
}
// upstreamErrors returns the modelBaseUrls failures of the latest listModels call.
func (a *openaiAdapter) upstreamErrors() []upstreamFailure {
a.upstreamMu.Lock()
defer a.upstreamMu.Unlock()
return append([]upstreamFailure(nil), a.upstreamErrs...)
}
func (a *openaiAdapter) setUpstreamErrors(errs []upstreamFailure) {
a.upstreamMu.Lock()
a.upstreamErrs = errs
a.upstreamMu.Unlock()
}
// listModels implements providerAdapter. It queries baseURL and every // listModels implements providerAdapter. It queries baseURL and every
// distinct modelBaseUrls upstream; an id counts only when the upstream // distinct modelBaseUrls upstream; an id counts only when the upstream
// that lists it is the one requests for that id are routed to. Any failing // that lists it is the one requests for that id are routed to. A baseURL
// upstream fails the whole listing, so a refresh never drops the models of // failure fails the listing, so a refresh never drops the models of a
// an upstream that is briefly down. // down baseURL. A failing modelBaseUrls upstream is recorded (see
// upstreamErrors) and skipped: its configured models stay served, and the
// other upstreams' ids still merge.
func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) { func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) {
var ids []string var ids []string
var failures []upstreamFailure
seen := make(map[string]bool) seen := make(map[string]bool)
for _, base := range a.upstreamBases() { for i, base := range a.upstreamBases() {
listed, err := a.listModelsFrom(ctx, base) listed, err := a.listModelsFrom(ctx, base)
if err != nil { if err != nil {
return nil, err if i == 0 || ctx.Err() != nil {
a.setUpstreamErrors(nil)
return nil, err
}
failures = append(failures, upstreamFailure{Upstream: base, Err: err.Error()})
continue
} }
for _, id := range listed { for _, id := range listed {
if a.baseForModel(id) != base || seen[id] { if a.baseForModel(id) != base || seen[id] {
@@ -462,6 +499,7 @@ func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) {
ids = append(ids, id) ids = append(ids, id)
} }
} }
a.setUpstreamErrors(failures)
return ids, nil return ids, nil
} }
+79 -7
View File
@@ -382,6 +382,9 @@ func (st *providerState) tryBeginWarmFillRetry(sinceWarmFill time.Time) bool {
return true return true
} }
// upstreamErrLogEvery bounds how often a provider's tolerated upstream failures are logged.
const upstreamErrLogEvery = 10 * time.Minute
// finishRefresh records the outcome of a refresh attempt started by // finishRefresh records the outcome of a refresh attempt started by
// tryBeginRefresh (or, for the synchronous warm fill, run unconditionally). // tryBeginRefresh (or, for the synchronous warm fill, run unconditionally).
// lastRefresh always advances to now, on success or failure alike — that is // lastRefresh always advances to now, on success or failure alike — that is
@@ -721,6 +724,8 @@ type modelRegistry struct {
modelMeta map[string]*ModelMetaConfig modelMeta map[string]*ModelMetaConfig
nowFn func() time.Time nowFn func() time.Time
warned map[string]bool warned map[string]bool
// upstreamErrLogAt is each provider's last upstream-failure log time; guarded by warnedMu.
upstreamErrLogAt map[string]time.Time
// routerShadowClean maps a router name to modelsGen+1 of its last collision-free scan; guarded by warnedMu. // routerShadowClean maps a router name to modelsGen+1 of its last collision-free scan; guarded by warnedMu.
routerShadowClean map[string]int64 routerShadowClean map[string]int64
// modelsCache holds one encoded GET /v1/models response body per // modelsCache holds one encoded GET /v1/models response body per
@@ -864,6 +869,7 @@ func newModelRegistry(adapters map[string]providerAdapter, cfg *Config, log func
warmFillRetryDelay: warmFillRetryDelay, warmFillRetryDelay: warmFillRetryDelay,
warmFillTimeout: warmFillTimeout, warmFillTimeout: warmFillTimeout,
warned: make(map[string]bool), warned: make(map[string]bool),
upstreamErrLogAt: make(map[string]time.Time),
routerShadowClean: make(map[string]int64), routerShadowClean: make(map[string]int64),
providerNames: make([]string, 0, len(adapters)), providerNames: make([]string, 0, len(adapters)),
modelsCache: make(map[string]modelsCacheEntry), modelsCache: make(map[string]modelsCacheEntry),
@@ -1095,6 +1101,39 @@ func (m *modelRegistry) discoveryHealthy(name string) bool {
func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []string, err error) { func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []string, err error) {
st.finishRefresh(now, ids, err) st.finishRefresh(now, ids, err)
atomic.AddInt64(&m.modelsGen, 1) atomic.AddInt64(&m.modelsGen, 1)
if err == nil {
m.logUpstreamErrors(st.name, now)
}
}
// logUpstreamErrors logs name's tolerated modelBaseUrls failures, at most once per upstreamErrLogEvery per provider.
func (m *modelRegistry) logUpstreamErrors(name string, now time.Time) {
adapter := m.adapters[name]
if adapter == nil {
return
}
rep, ok := adapter.(upstreamErrorReporter)
if !ok {
return
}
errs := rep.upstreamErrors()
if len(errs) == 0 {
return
}
m.warnedMu.Lock()
due := now.Sub(m.upstreamErrLogAt[name]) >= upstreamErrLogEvery
if due {
m.upstreamErrLogAt[name] = now
}
m.warnedMu.Unlock()
if !due {
return
}
base := adapter.base()
for _, f := range errs {
m.log("%s", fmt.Sprintf("model registry: discovery of provider %q upstream %s failed: %v",
name, sanitizeBaseURL(f.Upstream), sanitizeProviderErr(sanitizeProviderErr(f.Err, f.Upstream), base)))
}
} }
// warmFillFailure records ONE provider whose synchronous warmFill // warmFillFailure records ONE provider whose synchronous warmFill
@@ -2357,13 +2396,15 @@ type providerSnapshot struct {
// (feat/provider-health) — see providerState.snapshot's doc comment // (feat/provider-health) — see providerState.snapshot's doc comment
// for why it is read in the same locked pass as the rest of this // for why it is read in the same locked pass as the rest of this
// struct's fields. // struct's fields.
openUntil time.Time openUntil time.Time
name string name string
typeName string typeName string
baseURL string baseURL string
lastErr string lastErr string
models []string models []string
modelCount int // upstreamErrs lists modelBaseUrls upstreams that failed the latest discovery without failing the provider.
upstreamErrs []upstreamFailure
modelCount int
// health mirrors providerState's own field of the same name (feat/ // health mirrors providerState's own field of the same name (feat/
// provider-health): the admin dashboard's breaker-state column. Every // provider-health): the admin dashboard's breaker-state column. Every
// provider reads closed until a discovery failure actually trips its // provider reads closed until a discovery failure actually trips its
@@ -2414,6 +2455,29 @@ func (m *modelRegistry) aliasSnapshot() []aliasSnapshotEntry {
return out return out
} }
// aliasTargetCanonical resolves an alias target to the canonical
// "provider/model" id resolveAliasTarget would pick, ignoring group
// authorization: a provider-prefixed target resolves on that provider,
// a bare one on the sorted-first provider that knows it. ok is false for
// a target no provider knows yet.
func (m *modelRegistry) aliasTargetCanonical(target string) (string, bool) {
providerName, model, prefixed := m.splitConfiguredProvider(target)
if !prefixed {
model = target
for _, name := range m.providerNames {
if m.states[name].hasModel(model) {
providerName = name
break
}
}
}
if providerName == "" || !m.states[providerName].hasModel(model) {
return "", false
}
canonical := providerModelScopeID(providerName, model)
return canonical, true
}
// snapshot returns every configured provider's read-only view, sorted by // snapshot returns every configured provider's read-only view, sorted by
// name (m.providerNames is already sorted at construction) — the admin // name (m.providerNames is already sorted at construction) — the admin
// dashboard's provider table (spec §4, v0.2). // dashboard's provider table (spec §4, v0.2).
@@ -2440,7 +2504,15 @@ func (m *modelRegistry) snapshot() []providerSnapshot {
discoveryEnabled: m.states[name].discoveryEnabled, discoveryEnabled: m.states[name].discoveryEnabled,
health: health, health: health,
openUntil: openUntil, openUntil: openUntil,
upstreamErrs: upstreamErrorsOf(adapter),
}) })
} }
return out return out
} }
func upstreamErrorsOf(adapter providerAdapter) []upstreamFailure {
if rep, ok := adapter.(upstreamErrorReporter); ok {
return rep.upstreamErrors()
}
return nil
}
+98 -6
View File
@@ -2,6 +2,7 @@ package traefikllmgateway
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -57,22 +58,113 @@ func TestOpenAIAdapter_ModelBaseURLs_DiscoveryAndMetadataQueryEveryUpstream(t *t
assert.EqualValues(t, 2, hitsB.Load(), "shared modelBaseUrls upstream queried once per call, not once per model") assert.EqualValues(t, 2, hitsB.Load(), "shared modelBaseUrls upstream queried once per call, not once per model")
} }
func statusServer(t *testing.T, code int) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(code)
}))
t.Cleanup(srv.Close)
return srv
}
func TestOpenAIAdapter_ModelBaseURLs_FailingUpstream(t *testing.T) { func TestOpenAIAdapter_ModelBaseURLs_FailingUpstream(t *testing.T) {
t.Parallel() t.Parallel()
good := modelsServer(t, `{"data":[{"id":"main-model","max_model_len":1000}]}`, nil) good := modelsServer(t, `{"data":[{"id":"main-model","max_model_len":1000}]}`, nil)
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { bad := statusServer(t, http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
}))
t.Cleanup(bad.Close)
ad := newOpenAIAdapter("d1", good.URL, "") ad := newOpenAIAdapter("d1", good.URL, "")
ad.modelBases = map[string]string{"glm": bad.URL} ad.modelBases = map[string]string{"glm": bad.URL}
ad.metadataPath = "/v1/models" ad.metadataPath = "/v1/models"
_, err := ad.listModels(context.Background()) ids, err := ad.listModels(context.Background())
assert.Error(t, err, "discovery must fail rather than drop the failing upstream's models") require.NoError(t, err, "a failing modelBaseUrls upstream must not fail discovery")
assert.Equal(t, []string{"main-model"}, ids)
errs := ad.upstreamErrors()
require.Len(t, errs, 1)
assert.Equal(t, bad.URL, errs[0].Upstream)
got, err := ad.fetchModelMetadata(context.Background()) got, err := ad.fetchModelMetadata(context.Background())
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, map[string]int{"main-model": 1000}, got, "metadata keeps the healthy upstream's ids") assert.Equal(t, map[string]int{"main-model": 1000}, got, "metadata keeps the healthy upstream's ids")
} }
func TestOpenAIAdapter_BaseURLFailure_FailsDiscovery(t *testing.T) {
t.Parallel()
good := modelsServer(t, `{"data":[{"id":"glm"}]}`, nil)
bad := statusServer(t, http.StatusBadGateway)
ad := newOpenAIAdapter("d1", bad.URL, "")
ad.modelBases = map[string]string{"glm": good.URL}
_, err := ad.listModels(context.Background())
assert.Error(t, err)
assert.Empty(t, ad.upstreamErrors())
}
// Mirrors uni on d1: a TEI upstream answering 404 and a scaled-to-zero
// reranker answering 502 must not degrade the provider.
func TestGateway_ModelBaseURLsFailures_ProviderStaysHealthy(t *testing.T) {
t.Parallel()
main := modelsServer(t, `{"data":[{"id":"main-model"}]}`, nil)
other := modelsServer(t, `{"data":[{"id":"glm"},{"id":"main-model"}]}`, nil)
tei := statusServer(t, http.StatusNotFound)
rerank := statusServer(t, http.StatusBadGateway)
cfg := newAdminTestConfig()
cfg.Providers = map[string]*ProviderConfig{
"uni": {
Type: "openai", BaseURL: main.URL, APIKey: "sk", Discovery: true,
Models: []string{"e5-tei", "reranker"},
ModelBaseURLs: map[string]string{
"glm": other.URL, "e5-tei": tei.URL, "reranker": rerank.URL,
},
},
}
h, _ := newAdminGatewayHandle(t, cfg)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var got adminOverviewResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Len(t, got.Providers, 1)
p := got.Providers[0]
assert.Empty(t, p.LastErr)
assert.Equal(t, "closed", p.HealthState)
assert.Equal(t, []string{"e5-tei", "glm", "main-model", "reranker"}, p.Models)
require.Len(t, p.UpstreamErrors, 2)
byUp := map[string]string{}
for _, e := range p.UpstreamErrors {
byUp[e.Upstream] = e.Error
}
assert.Contains(t, byUp[tei.URL], "404")
assert.Contains(t, byUp[rerank.URL], "502")
assert.Contains(t, rec.Body.String(), `"upstreamErrors"`)
}
func TestGateway_BaseURLFailure_ProviderDegradedAsBefore(t *testing.T) {
t.Parallel()
bad := statusServer(t, http.StatusNotFound)
good := modelsServer(t, `{"data":[{"id":"glm"}]}`, nil)
cfg := newAdminTestConfig()
cfg.Providers = map[string]*ProviderConfig{
"uni": {
Type: "openai", BaseURL: bad.URL, APIKey: "sk", Discovery: true,
Models: []string{"glm"},
ModelBaseURLs: map[string]string{"glm": good.URL},
},
}
h, _ := newAdminGatewayHandle(t, cfg)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var got adminOverviewResponse
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Len(t, got.Providers, 1)
assert.Contains(t, got.Providers[0].LastErr, "404")
assert.Empty(t, got.Providers[0].UpstreamErrors)
}
+11
View File
@@ -10,12 +10,14 @@ import { useHashState } from '@/composables/useHashState'
import AppLayout from '@/layout/AppLayout.vue' import AppLayout from '@/layout/AppLayout.vue'
import type { PageId } from '@/lib/pages' import type { PageId } from '@/lib/pages'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import { useCatalogStore } from '@/stores/catalog'
import { useConfigStore } from '@/stores/config' import { useConfigStore } from '@/stores/config'
import { useDashboardStore } from '@/stores/dashboard' import { useDashboardStore } from '@/stores/dashboard'
import { useNavStore } from '@/stores/nav' import { useNavStore } from '@/stores/nav'
import { resetSessionData } from '@/stores/session' import { resetSessionData } from '@/stores/session'
const auth = useAuthStore() const auth = useAuthStore()
const catalog = useCatalogStore()
const config = useConfigStore() const config = useConfigStore()
const dashboard = useDashboardStore() const dashboard = useDashboardStore()
const nav = useNavStore() const nav = useNavStore()
@@ -65,6 +67,15 @@ watch(
}, },
) )
// Every model-id cell marks an alias from the catalog's alias list, so load it once per key.
watch(
() => auth.apiKey,
() => {
if (auth.isAuthenticated) void catalog.ensureLoaded()
},
{ immediate: true },
)
onMounted(() => { onMounted(() => {
dashboard.startPolling() dashboard.startPolling()
}) })
+39
View File
@@ -0,0 +1,39 @@
import { createPinia, setActivePinia } from 'pinia'
import { describe, expect, it } from 'vitest'
import { aliasTargetMap } from '@/lib/alias-display'
import { useCatalogStore } from '@/stores/catalog'
import type { AdminAliasView, AdminCatalogResponse } from '@/types/api'
const meta = {} as AdminAliasView['modelMeta']
describe('aliasTargetMap', () => {
it('prefers the resolved canonical target', () => {
const m = aliasTargetMap([{ alias: 'model-fast', target: 'deepseek-v4.1-flash-1017', resolvedTarget: 'uni/deepseek-v4.1-flash-1017', modelMeta: meta }])
expect(m.get('model-fast')).toBe('uni/deepseek-v4.1-flash-1017')
})
it('falls back to the configured target when it does not resolve', () => {
const m = aliasTargetMap([{ alias: 'ghost', target: 'no-such-model', modelMeta: meta }])
expect(m.get('ghost')).toBe('no-such-model')
})
it('is empty for no aliases and ignores non-alias ids', () => {
expect(aliasTargetMap(undefined).size).toBe(0)
expect(aliasTargetMap([]).get('uni/x')).toBeUndefined()
})
})
describe('useCatalogStore.aliasTargets', () => {
it('indexes the fetched catalog aliases', () => {
setActivePinia(createPinia())
const catalog = useCatalogStore()
expect(catalog.aliasTargets.size).toBe(0)
catalog.data = {
providers: [],
aliases: [{ alias: 'model-fast', target: 'x', resolvedTarget: 'uni/x', modelMeta: meta }],
} as AdminCatalogResponse
expect(catalog.aliasTargets.get('model-fast')).toBe('uni/x')
expect(catalog.aliasTargets.get('uni/x')).toBeUndefined()
})
})
+8
View File
@@ -0,0 +1,8 @@
import type { AdminAliasView } from '@/types/api'
/** Maps each alias id to the target a reader should see: the canonical `provider/model` when the gateway resolved it, else the configured target. */
export function aliasTargetMap(aliases: readonly AdminAliasView[] | undefined): Map<string, string> {
const map = new Map<string, string>()
for (const a of aliases ?? []) map.set(a.alias, a.resolvedTarget || a.target)
return map
}
+24 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { groupByProvider, priceStatus, selectModels } from '@/lib/models-view' import { groupByProvider, modelFilterFields, priceStatus, selectModels } from '@/lib/models-view'
import type { ModelCatalogRow } from '@/lib/model-table-columns' import type { ModelCatalogRow } from '@/lib/model-table-columns'
function row(id: string, over: Partial<ModelCatalogRow> = {}): ModelCatalogRow { function row(id: string, over: Partial<ModelCatalogRow> = {}): ModelCatalogRow {
@@ -68,3 +68,26 @@ describe('groupByProvider', () => {
expect(g!.rows.map((r) => r.id)).toEqual(['a/c', 'a/a', 'a/b']) expect(g!.rows.map((r) => r.id)).toEqual(['a/c', 'a/a', 'a/b'])
}) })
}) })
const selectsWithoutOptions = (fields: ReturnType<typeof modelFilterFields>) =>
fields.filter((f) => f.type === 'select' && (!f.options || f.options.length === 0))
describe('modelFilterFields', () => {
it('never yields a select with empty options before data loads', () => {
const fields = modelFilterFields([], [])
expect(selectsWithoutOptions(fields)).toEqual([])
expect(fields.map((f) => f.id)).toEqual(['kind', 'price'])
})
it('adds the provider select once providers are known, sorted and deduplicated', () => {
const fields = modelFilterFields(['uni', 'a', 'uni'], ['chat'])
const provider = fields.find((f) => f.id === 'provider')
expect(provider?.options?.map((o) => o.value)).toEqual(['a', 'uni'])
})
it('keeps a provider from the URL selectable before the data arrives', () => {
const fields = modelFilterFields([], [], 'uni')
expect(selectsWithoutOptions(fields)).toEqual([])
expect(fields.find((f) => f.id === 'provider')?.options).toEqual([{ value: 'uni', label: 'uni' }])
})
})
+22
View File
@@ -1,3 +1,5 @@
import type { FilterField } from '@perfect-design/ui'
import { filterModelRows } from '@/lib/model-filter' import { filterModelRows } from '@/lib/model-filter'
import type { ModelCatalogRow } from '@/lib/model-table-columns' import type { ModelCatalogRow } from '@/lib/model-table-columns'
@@ -50,3 +52,23 @@ export function groupByProvider(rows: ModelCatalogRow[]): ProviderGroup[] {
for (const g of groups.values()) g.rows.sort(byTraffic) for (const g of groups.values()) g.rows.sort(byTraffic)
return [...groups.values()] return [...groups.values()]
} }
const PRICE_OPTIONS: Array<{ value: PriceStatus; label: string }> = [
{ value: 'priced', label: 'Priced' },
{ value: 'unpriced', label: 'Unpriced' },
{ value: 'free', label: 'Free' },
]
/**
* FilterBar throws on a select without options, so the provider select is
* omitted until a provider is known; a provider already in the URL counts as known.
*/
export function modelFilterFields(providers: string[], kinds: string[], activeProvider?: string): FilterField[] {
const names = [...new Set([...providers, ...(activeProvider ? [activeProvider] : [])])].sort()
const toOptions = (vs: string[]) => vs.map((v) => ({ value: v, label: v }))
return [
...(names.length > 0 ? [{ id: 'provider', label: 'Provider', type: 'select' as const, operators: ['eq' as const], options: toOptions(names) }] : []),
{ id: 'kind', label: 'Kind', type: 'select', operators: ['eq'], options: [{ value: NO_KIND, label: 'No kind' }, ...toOptions(kinds)] },
{ id: 'price', label: 'Price', type: 'select', operators: ['eq'], options: PRICE_OPTIONS },
]
}
+3 -12
View File
@@ -5,7 +5,7 @@ import { computed, onMounted, reactive, watch } from 'vue'
import { formatCompactCount, formatContextWindow, formatModelCostHover } from '@/lib/format' import { formatCompactCount, formatContextWindow, formatModelCostHover } from '@/lib/format'
import { loadState } from '@/lib/load-state' import { loadState } from '@/lib/load-state'
import { NO_KIND, groupByProvider, priceStatus, selectModels } from '@/lib/models-view' import { groupByProvider, modelFilterFields, priceStatus, selectModels } from '@/lib/models-view'
import type { ModelSelection, PriceStatus } from '@/lib/models-view' import type { ModelSelection, PriceStatus } from '@/lib/models-view'
import { pageWindow } from '@/lib/paging' import { pageWindow } from '@/lib/paging'
import { resolveSel } from '@/lib/panel-selection' import { resolveSel } from '@/lib/panel-selection'
@@ -30,11 +30,6 @@ const PAGE_SIZE = 12
const ROUTER_BADGES = 2 const ROUTER_BADGES = 2
const FILTER_KEYS = ['provider', 'kind', 'price'] as const const FILTER_KEYS = ['provider', 'kind', 'price'] as const
type FilterKey = (typeof FILTER_KEYS)[number] type FilterKey = (typeof FILTER_KEYS)[number]
const PRICE_OPTIONS: Array<{ value: PriceStatus; label: string }> = [
{ value: 'priced', label: 'Priced' },
{ value: 'unpriced', label: 'Unpriced' },
{ value: 'free', label: 'Free' },
]
const HEALTH_TONE = { healthy: 'success', degraded: 'warning', severe: 'danger' } as const const HEALTH_TONE = { healthy: 'success', degraded: 'warning', severe: 'danger' } as const
const BREAKER_TONE = { closed: 'success', open: 'danger', 'half-open': 'warning', degraded: 'warning' } as const const BREAKER_TONE = { closed: 'success', open: 'danger', 'half-open': 'warning', degraded: 'warning' } as const
@@ -88,12 +83,8 @@ const filtering = computed(() => query.value.trim() !== '' || FILTER_KEYS.some((
const overviewProviders = computed(() => dashboard.overview?.providers ?? []) const overviewProviders = computed(() => dashboard.overview?.providers ?? [])
const fields = computed<FilterField[]>(() => { const fields = computed<FilterField[]>(() => {
const kinds = [...new Set(models.rows.map((r) => r.kind).filter((k) => k !== ''))].sort() const kinds = [...new Set(models.rows.map((r) => r.kind).filter((k) => k !== ''))].sort()
const providers = [...new Set([...overviewProviders.value.map((p) => p.name), ...models.rows.map((r) => r.providerName)])].sort() const providers = [...overviewProviders.value.map((p) => p.name), ...models.rows.map((r) => r.providerName)]
return [ return modelFilterFields(providers, kinds, nav.params.provider)
{ id: 'provider', label: 'Provider', type: 'select', operators: ['eq'], options: providers.map((p) => ({ value: p, label: p })) },
{ id: 'kind', label: 'Kind', type: 'select', operators: ['eq'], options: [{ value: NO_KIND, label: 'No kind' }, ...kinds.map((k) => ({ value: k, label: k }))] },
{ id: 'price', label: 'Price', type: 'select', operators: ['eq'], options: PRICE_OPTIONS },
]
}) })
const filterItems = computed<FilterItem[]>(() => const filterItems = computed<FilterItem[]>(() =>
FILTER_KEYS.filter((k) => nav.params[k]).map((k) => ({ id: k, field: k, operator: 'eq', value: nav.params[k]! })), FILTER_KEYS.filter((k) => nav.params[k]).map((k) => ({ id: k, field: k, operator: 'eq', value: nav.params[k]! })),
+5
View File
@@ -1,5 +1,6 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { aliasTargetMap } from '@/lib/alias-display'
import { adminFetch, isAuthRejection, messageOf } from '@/lib/api' import { adminFetch, isAuthRejection, messageOf } from '@/lib/api'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import type { AdminCatalogModel, AdminCatalogResponse } from '@/types/api' import type { AdminCatalogModel, AdminCatalogResponse } from '@/types/api'
@@ -58,6 +59,10 @@ export const useCatalogStore = defineStore('catalog', {
} }
return map return map
}, },
/** aliasTargets maps each configured alias id to the model it points at, so any view listing a requested model id can mark an alias. */
aliasTargets(state): Map<string, string> {
return aliasTargetMap(state.data?.aliases)
},
}, },
actions: { actions: {
/** /**
+2
View File
@@ -365,6 +365,8 @@ export interface AdminRouterView {
export interface AdminAliasView { export interface AdminAliasView {
alias: string alias: string
target: string target: string
/** Canonical `provider/model` id the target resolves to; absent while it resolves to no known model. */
resolvedTarget?: string
/** /**
* The alias's own resolved metadata (admin.go: adminAliasView. * The alias's own resolved metadata (admin.go: adminAliasView.
* ModelMeta — feature v0.23): INHERITED from its target unless the * ModelMeta — feature v0.23): INHERITED from its target unless the
+6 -1
View File
@@ -1,15 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import { Badge } from '@perfect-design/ui'
import { computed } from 'vue' import { computed } from 'vue'
import { splitModelId } from '@/lib/model-id' import { splitModelId } from '@/lib/model-id'
import { useCatalogStore } from '@/stores/catalog'
const props = defineProps<{ id: string; bare?: boolean }>() const props = defineProps<{ id: string; bare?: boolean }>()
const parts = computed(() => splitModelId(props.id)) const parts = computed(() => splitModelId(props.id))
const catalog = useCatalogStore()
const target = computed(() => catalog.aliasTargets.get(props.id) ?? null)
</script> </script>
<template> <template>
<span class="wb-model" :title="id"> <span class="wb-model" :title="target ? `${id} → ${target}` : id">
<span v-if="parts.provider && !bare" class="wb-model-provider">{{ parts.provider }}</span> <span v-if="parts.provider && !bare" class="wb-model-provider">{{ parts.provider }}</span>
<span class="wb-model-name">{{ parts.model }}</span> <span class="wb-model-name">{{ parts.model }}</span>
<Badge v-if="target" tone="neutral" variant="outline" size="sm" class="wb-model-alias ml-1 min-w-0 truncate font-mono">alias → {{ target }}</Badge>
</span> </span>
</template> </template>