diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 381e1f1e7..f420d0654 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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 diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 450a96e73..2ec9eff8c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) { diff --git a/internal/gateway/models_wait.go b/internal/gateway/models_wait.go index 808f5dd42..07babdab6 100644 --- a/internal/gateway/models_wait.go +++ b/internal/gateway/models_wait.go @@ -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 +} diff --git a/internal/gateway/models_wait_test.go b/internal/gateway/models_wait_test.go index 10b8f1770..d15fb640a 100644 --- a/internal/gateway/models_wait_test.go +++ b/internal/gateway/models_wait_test.go @@ -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) } diff --git a/internal/provider/remote_follow.go b/internal/provider/remote_follow.go index 1f8001ffc..218829011 100644 --- a/internal/provider/remote_follow.go +++ b/internal/provider/remote_follow.go @@ -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) diff --git a/internal/provider/remote_follow_test.go b/internal/provider/remote_follow_test.go index c913640ff..977af9572 100644 --- a/internal/provider/remote_follow_test.go +++ b/internal/provider/remote_follow_test.go @@ -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) {