gateway: /v1/models answers its ETag, and 304 to a client that has the list already

clyzhicore (Discord) runs a server magpie as the gateway and a local magpie
that takes its /v1/models and writes the models into dsh. They asked for
an ETag or a list you can wait on, so the local side knows a change at
once and a dead connection costs little. The wait is there since
06c4582cc (v0.1.3172: X-Magpie-List-Wait with If-None-Match, and the
Remote magpie follower). What was missing, and is added here:

- A plain GET /v1/models (no wait header) is answered with the same ETag
  a wait answers (listTag of the bytes this caller gets), Cache-Control
  private, no-cache, and 304 with no body, at once, when If-None-Match
  names it (strong or W/, in a comma list, or *). A tag it doesn't name,
  or none, is answered the list as before, same bytes. A refused list
  (400) stays untagged. Any client (a script, curl, another tool) can
  now poll cheaply.
- A wait's answer, 200 or 304, says in X-Magpie-List-Wait how many
  seconds it held. A plain answer doesn't.
- The follower (waitRemoteList) takes a 304 that comes sooner than
  followQuick (5s) without that header as a magpie that doesn't wait.
  This guards the change above: a proxy that drops X-Magpie-List-Wait
  would now get a tagged plain list and an instant 304, and the follower
  would ask every followGap (1s). It now leaves such a magpie to its
  schedule and asks again after followOldAgain (1h), as for one from
  before the wait. Servers from 06c4582cc on hold each wait to its end
  (50s), so their 304s pass.

Compatibility: an old server (no ETag) is still left to the schedule,
as TestRemoteMagpieOldListNotFollowed checks. An old client never sends
If-None-Match without the wait header and gets the same bytes plus an
ETag. The GUI doesn't read the gateway's /v1/models through Wails (whose
304 on WebView2 is a 505, gui/api.go writeJSONSame), so that doesn't
apply.

Hidden models (their second ask) already exist and are not changed: a
provider's "Only through routing groups" (Provider.Unlisted, `magpie
provider listed <id> no`) and a group's listed=no (Group.Unlists, `magpie
group set ... listed=no`, CLI only) keep models out of /v1/models while
groups still route to them.

docs/subsystems/gateway-routing.md says the above.

Run (on mote, through mote-run, first at 04ed05733):
- gofmt -l on the changed packages: clean.
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...; go build ., GOOS=linux -tags nogui, GOOS=windows: all ok.
- go test -tags nogui -race -count=1 -timeout 90m ./internal/gateway:
  ok 2145s, no DATA RACE (mote at load ~100-130).
- go test -tags nogui -count=1 -timeout 45m ./internal/provider: ok 126s.
- After rebasing onto origin/main (5 commits, none in these files):
  gofmt -l clean; go vet (darwin, linux nogui, windows) of both
  packages ok; -race -run "ModelsWait|ModelsList|RemoteMagpie": gateway
  ok 12.5s, provider ok 4.8s.

Broken by hand, each red:
- models() back to listModels (no tag on the plain list):
  TestModelsListConditional ("ETag \"\"") and TestModelsWaitTagged ("a
  plain list: 200, ETag \"\"").
- tagNamed never matching: TestModelsListConditional (200 with the body
  for each of the tag, W/, a list and *).
- No X-Magpie-List-Wait on a wait's answers: TestModelsWaitTagged ("a
  wait's list says it held \"\"", same for its 304).
- The followQuick check off: TestRemoteMagpieStrippedWaitNotAskedOver
  ("asked 28 times in 300ms, want 2").

Not tried: two real magpies, or a real reverse proxy that drops the
header (the stripped case is a fake in the test). Not run on Windows or
Linux. The full suite (go test ./...) and the GUI suite: not run at push.
Following a provider added as a plain OpenAI-compatible endpoint (not the
Remote magpie type) is not done: its list URL comes from fetchOne's
several bases, and it still goes by its #2135 schedule.

Reported-by: clyzhicore (Discord)
This commit is contained in:
yetone
2026-11-08 15:45:57 +08:00
parent 15918265e3
commit 1aabc66fd1
6 changed files with 210 additions and 24 deletions
+13 -3
View File
@@ -573,10 +573,20 @@ looked at again on each of magpie's writes and on each change another
process makes to its files (`filememo.Written`), each look holding the
catalog for itself, so the wait is exempt from `holdCatalog`. It is the
list's own route, so the key, `lanGuard`, `corsGuard` and a key's models
judge it exactly as the list. A list asked without the header is answered
as before, with no ETag. `modelsOnceChanged` in
judge it exactly as the list. A wait's answer, 200 or 304, says in
`X-Magpie-List-Wait` how many seconds it held. A list asked without the
header is answered the same bytes with the same `ETag` (`private,
no-cache`), and 304 with no body, at once, when `If-None-Match` names it
(weakly, in a list, or `*`; clyzhicore on Discord), so a client polling
the list pays a few bytes while it is unchanged; a refused list (400) is
untagged. The follower (`waitRemoteList` in
[`remote_follow.go`](../../internal/provider/remote_follow.go)) takes a 304
that came sooner than `followQuick` and doesn't say it waited as a magpie
that doesn't wait (a proxy dropped the header), and leaves it to the
schedule rather than asking it each second. `modelsOnceChanged` and
`listModelsTagged` in
[`models_wait.go`](../../internal/gateway/models_wait.go), and
`TestModelsWaitGuardedAsTheList` in
`TestModelsWaitGuardedAsTheList` and `TestModelsListConditional` in
[`models_wait_test.go`](../../internal/gateway/models_wait_test.go).
A read-only gateway key (`access.Key.ReadOnly`, set by `add-key` or
+1 -1
View File
@@ -1570,7 +1570,7 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {
s.modelsOnceChanged(w, r)
return
}
s.listModels(w, r)
s.listModelsTagged(w, r)
}
func (s *Server) listModels(w http.ResponseWriter, r *http.Request) {
+54 -2
View File
@@ -26,7 +26,13 @@ import (
// of the wait, and as this gateway stops, 304 says it is the same. A list
// is looked at again on each write magpie makes and on each change
// another process makes to its files (filememo.Written), not polled.
// A client asking without the header is answered as before, no ETag.
// A client asking without the header is answered the list with the same
// ETag, and 304 with no body when its If-None-Match names it already
// (listModelsTagged): a script or a magpie polling the list pays a few
// bytes while it is unchanged (clyzhicore on Discord). A wait answer says
// in provider.ListWaitHeader how long it held, which a plain answer
// doesn't: a proxy that drops the header would turn the wait into a plain
// list, and its 304 alone can't tell the two apart.
// listWaitMost is the longest a wait for the list is held: under the
// minute a proxy in front of a gateway (nginx's proxy_read_timeout) lets
@@ -100,7 +106,9 @@ func (s *Server) lookAtList(r *http.Request) *listAnswer {
// If-None-Match names, or 304 at the end of the wait.
func (s *Server) modelsOnceChanged(w http.ResponseWriter, r *http.Request) {
since := strings.TrimSpace(r.Header.Get("If-None-Match"))
end := time.NewTimer(listWaitOf(r))
wait := listWaitOf(r)
held := strconv.Itoa(int(wait / time.Second))
end := time.NewTimer(wait)
defer end.Stop()
tag := ""
for {
@@ -114,6 +122,7 @@ func (s *Server) modelsOnceChanged(w http.ResponseWriter, r *http.Request) {
}
if a.status == http.StatusOK {
w.Header().Set("ETag", tag)
w.Header().Set(provider.ListWaitHeader, held)
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(a.status)
@@ -144,8 +153,51 @@ func (s *Server) modelsOnceChanged(w http.ResponseWriter, r *http.Request) {
}
others.Stop()
w.Header().Set("ETag", tag)
w.Header().Set(provider.ListWaitHeader, held)
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusNotModified)
return
}
}
// listModelsTagged answers r's list with its ETag, the one a wait for the
// list answers (listTag), and 304 with no body when r's If-None-Match
// names it already. The answer depends on who asks (a key's models, an
// agent's picks), so a cache must ask again each time (private,
// no-cache), and the tag is of the bytes this caller would be answered.
func (s *Server) listModelsTagged(w http.ResponseWriter, r *http.Request) {
a := &listAnswer{header: w.Header()}
s.listModels(a, r)
if a.status == 0 {
a.status = http.StatusOK
}
if a.status != http.StatusOK {
w.WriteHeader(a.status)
w.Write(a.body.Bytes())
return
}
tag := listTag(a.status, a.body.Bytes())
w.Header().Set("ETag", tag)
w.Header().Set("Cache-Control", "private, no-cache")
if tagNamed(r.Header.Get("If-None-Match"), tag) {
w.Header().Del("Content-Type")
w.Header().Del("Content-Length")
w.WriteHeader(http.StatusNotModified)
return
}
w.WriteHeader(http.StatusOK)
w.Write(a.body.Bytes())
}
// tagNamed reports whether an If-None-Match value names tag: one of its
// comma-separated tags, weak or strong (RFC 9110's weak comparison), or *.
func tagNamed(ifNoneMatch, tag string) bool {
want := strings.TrimPrefix(tag, "W/")
for t := range strings.SplitSeq(ifNoneMatch, ",") {
t = strings.TrimSpace(t)
if t == "*" || t != "" && strings.TrimPrefix(t, "W/") == want {
return true
}
}
return false
}
+83 -7
View File
@@ -31,27 +31,103 @@ func listAsk(t *testing.T, url, wait, tag string) (int, string, string) {
return res.StatusCode, res.Header.Get("ETag"), string(b)
}
// listHeld is the wait srv's list answer says it held.
func listHeld(t *testing.T, url, wait, tag string) string {
t.Helper()
req, _ := http.NewRequest("GET", url+"/v1/models", nil)
if wait != "" {
req.Header.Set(provider.ListWaitHeader, wait)
}
if tag != "" {
req.Header.Set("If-None-Match", tag)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res.Header.Get(provider.ListWaitHeader)
}
// A client polling the list with If-None-Match (clyzhicore on Discord: a
// magpie or a script following another's list) is answered 304 with no
// body, at once, while the list is the one it names, and the new list
// with its new tag once it changed. A tag it doesn't name, or none, is
// answered the list.
func TestModelsListConditional(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
srv := httptest.NewServer(New().Handler())
defer srv.Close()
_, tag, plain := listAsk(t, srv.URL, "", "")
if tag == "" || !strings.HasPrefix(tag, `"`) {
t.Fatalf("ETag %q", tag)
}
if _, again, body := listAsk(t, srv.URL, "", ""); again != tag || body != plain {
t.Fatalf("the same list asked again: ETag %q (was %q), same body %v", again, tag, body == plain)
}
for _, named := range []string{tag, "W/" + tag, `"other", ` + tag, "*"} {
code, again, body := listAsk(t, srv.URL, "", named)
if code != http.StatusNotModified || again != tag || body != "" {
t.Errorf("If-None-Match %s: %d, ETag %q, body %q; want 304 %s and none", named, code, again, body, tag)
}
}
if code, _, body := listAsk(t, srv.URL, "", `"ml-other"`); code != 200 || body != plain {
t.Errorf("another tag: %d, same body %v", code, body == plain)
}
if err := provider.Save(provider.Provider{ID: "fake2", Name: "Fake 2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil {
t.Fatal(err)
}
code, now, body := listAsk(t, srv.URL, "", tag)
if code != 200 || now == "" || now == tag || !strings.Contains(body, "m2") {
t.Fatalf("after a change: %d, ETag %q (was %q), m2 listed %v", code, now, tag, strings.Contains(body, "m2"))
}
// a list refused is answered as before, untagged
req, _ := http.NewRequest("GET", srv.URL+"/v1/models?kind=bogus", nil)
req.Header.Set("If-None-Match", "*")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != 400 || res.Header.Get("ETag") != "" {
t.Errorf("a refused list: %d, ETag %q; want 400 and none", res.StatusCode, res.Header.Get("ETag"))
}
}
// Another magpie waiting at the list (KaCli) is answered the list's ETag;
// the same list is held to the end of the wait and answered 304, and a
// list asked without the header is answered as before, with no ETag.
// the same list is held to the end of the wait and answered 304. A list
// asked without the header is answered the same bytes with the same ETag
// (clyzhicore), and only a wait's answer says how long it held.
func TestModelsWaitTagged(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
srv := httptest.NewServer(New().Handler())
defer srv.Close()
code, tag, plain := listAsk(t, srv.URL, "", "")
if code != 200 || tag != "" {
t.Fatalf("a plain list: %d, ETag %q; want 200 and none", code, tag)
code, plainTag, plain := listAsk(t, srv.URL, "", "")
if code != 200 || plainTag == "" {
t.Fatalf("a plain list: %d, ETag %q; want 200 and a tag", code, plainTag)
}
if held := listHeld(t, srv.URL, "", ""); held != "" {
t.Errorf("a plain list says it held %q", held)
}
code, tag, body := listAsk(t, srv.URL, "1", "")
if code != 200 || tag == "" || body != plain {
t.Fatalf("a wait with no tag: %d, ETag %q, same body %v", code, tag, body == plain)
if code != 200 || tag != plainTag || body != plain {
t.Fatalf("a wait with no tag: %d, ETag %q (plain %q), same body %v", code, tag, plainTag, body == plain)
}
if held := listHeld(t, srv.URL, "1", ""); held != "1" {
t.Errorf("a wait's list says it held %q, want 1", held)
}
start := time.Now()
code, again, _ := listAsk(t, srv.URL, "1", tag)
if code != http.StatusNotModified || again != tag {
t.Fatalf("the same list: %d, ETag %q; want 304 %q", code, again, tag)
}
if held := listHeld(t, srv.URL, "1", tag); held != "1" {
t.Errorf("a wait's 304 says it held %q, want 1", held)
}
if d := time.Since(start); d < 900*time.Millisecond {
t.Errorf("the same list answered after %v, before its wait ended", d)
}
+14 -1
View File
@@ -47,10 +47,16 @@ var (
// followLook is how often the providers followed are looked at again
// with no write of magpie's to say they changed
followLook = time.Minute
// followQuick: a 304 sooner than this that doesn't say it waited
// (ListWaitHeader) is from a magpie that didn't wait
followQuick = 5 * time.Second
)
// errListNotWaited is a magpie that answered the list at once, with no
// ETag: one from before ListWaitHeader.
// ETag: one from before ListWaitHeader. Or one whose 304 came at once and
// doesn't say it waited: a magpie that tags every list, reached through a
// proxy that dropped ListWaitHeader, which asked again would be asked
// each followGap.
var errListNotWaited = errors.New("its magpie doesn't wait for its list to change; fetched on its schedule")
// KeepRemoteListsFollowed follows the list of each Remote magpie the user
@@ -233,6 +239,7 @@ func waitRemoteList(ctx context.Context, p Provider, tag string) (string, error)
if tag != "" {
req.Header.Set("If-None-Match", tag)
}
asked := time.Now()
res, err := p.Do(http.DefaultClient, req)
if err != nil {
return "", err
@@ -241,6 +248,12 @@ func waitRemoteList(ctx context.Context, p Provider, tag string) (string, error)
io.Copy(io.Discard, io.LimitReader(res.Body, 64<<20))
switch {
case res.StatusCode == http.StatusNotModified:
// a magpie from before this one says no wait it held, and holds
// each wait to its end; a 304 at once is a gateway stopping, or a
// list that wasn't waited for
if res.Header.Get(ListWaitHeader) == "" && time.Since(asked) < followQuick {
return "", errListNotWaited
}
return tag, nil
case res.StatusCode != http.StatusOK:
return "", fmt.Errorf("%s answered %s", remoteName(p), res.Status)
+45 -10
View File
@@ -14,14 +14,18 @@ import (
// followFake is a magpie whose list is model, answered with its ETag, and
// held while a wait names that tag, as the gateway's modelsOnceChanged
// does. waits says whether it waits at all (one from before doesn't).
// does. waits says whether it waits at all (one from before doesn't),
// and stripped is a magpie that tags every list reached through a proxy
// that drops ListWaitHeader: it answers each ask at once, 304 when the
// tag is the list's, saying no wait.
type followFake struct {
mu sync.Mutex
model string
changed chan struct{}
waits bool
fetches atomic.Int32 // asked with no wait: the list fetched
asks atomic.Int32 // asked to wait
mu sync.Mutex
model string
changed chan struct{}
waits bool
stripped bool
fetches atomic.Int32 // asked with no wait: the list fetched
asks atomic.Int32 // asked to wait
}
func (f *followFake) set(model string) {
@@ -38,6 +42,19 @@ func (f *followFake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
waiting := r.Header.Get(ListWaitHeader) != ""
if f.stripped && waiting {
f.asks.Add(1)
f.mu.Lock()
tag := `"` + f.model + `"`
f.mu.Unlock()
w.Header().Set("ETag", tag)
if r.Header.Get("If-None-Match") == tag {
w.WriteHeader(http.StatusNotModified)
return
}
io.WriteString(w, `{"object":"list","data":[]}`)
return
}
if !waiting {
f.fetches.Add(1)
} else {
@@ -71,9 +88,12 @@ func (f *followFake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func followFast(t *testing.T) {
t.Helper()
gap, fail, old, look := followGap, followFailWait, followOldAgain, followLook
followGap, followFailWait, followOldAgain, followLook = 10*time.Millisecond, 50*time.Millisecond, time.Hour, 50*time.Millisecond
t.Cleanup(func() { followGap, followFailWait, followOldAgain, followLook = gap, fail, old, look })
gap, fail, old, look, quick := followGap, followFailWait, followOldAgain, followLook, followQuick
// the fake holds a wait 2s, far from followQuick
followGap, followFailWait, followOldAgain, followLook, followQuick = 10*time.Millisecond, 50*time.Millisecond, time.Hour, 50*time.Millisecond, 500*time.Millisecond
t.Cleanup(func() {
followGap, followFailWait, followOldAgain, followLook, followQuick = gap, fail, old, look, quick
})
}
func followedCount(id string) int {
@@ -168,6 +188,21 @@ func TestRemoteMagpieOldListNotFollowed(t *testing.T) {
}
}
// A magpie that tags every list (clyzhicore), reached through a proxy
// that drops ListWaitHeader, answers each wait at once: its first answer,
// tagged, can't be told from a wait's, but its 304 at once that says no
// wait is, and it is left to the schedule rather than asked each
// followGap.
func TestRemoteMagpieStrippedWaitNotAskedOver(t *testing.T) {
f := &followFake{model: "own/m1", changed: make(chan struct{}), stripped: true}
followRemote(t, f, "")
followUntil(t, "asked twice", func() bool { return f.asks.Load() >= 2 })
time.Sleep(300 * time.Millisecond)
if n := f.asks.Load(); n != 2 {
t.Errorf("a magpie that doesn't wait asked %d times in 300ms, want 2", n)
}
}
// A Remote magpie whose user set its list to be fetched only when asked
// is not followed: magpie's default never overrides the user's "off".
func TestRemoteMagpieOffNotFollowed(t *testing.T) {