Files
magpie/internal/gateway/models_wait.go
T
yetone 1aabc66fd1 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)
2026-11-08 15:45:57 +08:00

204 lines
6.6 KiB
Go

package gateway
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/provider"
)
// Another magpie that has this one as its provider (remote-magpie) waits
// here for this magpie's model list to change, and fetches it again when
// it has (KaCli on Discord: a route or group changed on the server reached
// the computer using it only on its next 10-minute fetch, and its agents'
// configs after that). It is the list's own route, GET /v1/models, so
// every guard a list asked for passes (the key, the origin, the network
// share, a key's models) holds for the wait as well, with
// provider.ListWaitHeader saying how many seconds to wait at most and
// If-None-Match the list it has (the ETag of its last answer). The list
// is answered, with its ETag, once it is other than that one; at the end
// 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 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
// an answer take.
const listWaitMost = 50 * time.Second
// listSettle is how long a write is given for the ones that come with it
// (a group saved, then the catalog touched) before the list is looked at.
var listSettle = 200 * time.Millisecond
// waitsForList reports whether r is another magpie waiting for the list to
// change.
func waitsForList(r *http.Request) bool {
if r.Method != http.MethodGet || r.Header.Get(provider.ListWaitHeader) == "" {
return false
}
return r.URL.Path == "/v1/models" || r.URL.Path == "/models"
}
// listWaitOf is how long r asks to wait, at most listWaitMost.
func listWaitOf(r *http.Request) time.Duration {
n, err := strconv.Atoi(strings.TrimSpace(r.Header.Get(provider.ListWaitHeader)))
if err != nil || n <= 0 {
return 0
}
return min(time.Duration(n)*time.Second, listWaitMost)
}
// listTag is a list answer's ETag: of the bytes answered, so it moves
// exactly when what another magpie would fetch does.
func listTag(status int, body []byte) string {
h := sha256.New()
h.Write([]byte(strconv.Itoa(status)))
h.Write(body)
return `"ml-` + hex.EncodeToString(h.Sum(nil)[:12]) + `"`
}
// listAnswer is the list as r would be answered it now.
type listAnswer struct {
header http.Header
status int
body bytes.Buffer
}
func (a *listAnswer) Header() http.Header { return a.header }
func (a *listAnswer) WriteHeader(code int) {
if a.status == 0 {
a.status = code
}
}
func (a *listAnswer) Write(b []byte) (int, error) {
a.WriteHeader(http.StatusOK)
return a.body.Write(b)
}
// lookAtList answers r's list into a listAnswer, holding the catalog and
// files it reads for the one look, as holdCatalog does for a request.
func (s *Server) lookAtList(r *http.Request) *listAnswer {
a := &listAnswer{header: http.Header{}}
release, held := provider.Hold(), filememo.Hold()
defer release()
defer held()
s.listModels(a, r)
if a.status == 0 {
a.status = http.StatusOK
}
return a
}
// modelsOnceChanged answers r's list once it is other than the one r's
// 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"))
wait := listWaitOf(r)
held := strconv.Itoa(int(wait / time.Second))
end := time.NewTimer(wait)
defer end.Stop()
tag := ""
for {
// before the look, so a write made during it isn't missed
written := filememo.Written()
a := s.lookAtList(r)
tag = listTag(a.status, a.body.Bytes())
if a.status != http.StatusOK || tag != since {
for k, v := range a.header {
w.Header()[k] = v
}
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)
w.Write(a.body.Bytes())
return
}
// another process's writes are seen at once while filememo.Watch
// runs, and every few seconds where it can't
others := time.NewTimer(filememo.OthersEvery())
select {
case <-r.Context().Done():
others.Stop()
return
case <-s.streamsEnding():
case <-end.C:
case <-written:
others.Stop()
settle := time.NewTimer(listSettle)
select {
case <-r.Context().Done():
settle.Stop()
return
case <-settle.C:
}
continue
case <-others.C:
continue
}
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
}