Files
magpie/internal/gateway/models_wait_test.go
T
yetone 06c4582cca remote magpie: a list changed on the other magpie reaches this one's agents at once
KaCli (Discord) runs two magpies: the server's is the gateway, and the
local one has it as a Remote magpie and writes its models into dsh. A
route or group changed on the server reached the local dsh only on the
next 10-minute fetch (#2135's RemoteMagpieEvery). The server knows when
its list changes (filememo), so it now says so.

- Server: GET /v1/models with X-Magpie-List-Wait: <secs> and
  If-None-Match answers the list with an ETag once it differs from that
  tag. It answers 304 at the end of the wait (at most 50s, under a
  proxy's 60s) or as the gateway stops. The list is looked at again on
  each magpie write and on each change another process makes to its
  files (filememo.Written). It is the list's own route, so the key,
  lanGuard, corsGuard and a key's models judge it as before. The wait is
  exempt from holdCatalog, and each look holds the catalog for itself.
  Without the header the answer is the same as before, with no ETag.
- Client: KeepRemoteListsFollowed (started beside KeepListsFresh) keeps
  one long-poll per Remote magpie. On a new tag it fetches the list
  through the same RefetchTaking, so catalog.Touched rewrites the
  agents' configs. A magpie from before answers at once with no ETag; it
  is left to the 10m schedule and asked again after an hour. A Remote
  magpie whose user set its list to "off" is not followed. The schedule
  stays as the fallback.

Run (on mote, through mote-run):
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build ./..., GOOS=linux -tags nogui and
  GOOS=windows builds: all ok.
- go test -tags nogui -count=1 ./internal/gateway ./internal/provider
  ./internal/catalog ./internal/filememo: all ok (gateway 863s, provider 152s, catalog, filememo).
- After the rebase on 650bf8412 (11 files changed under gateway and
  provider since): go vet of both, go build ./..., and -run
  "ModelsWait|RemoteMagpie|ListsFresh|HoldCatalog|Models" of both: ok.
- Two real magpies (this build, `serve`, sandbox HOMEs, 127.0.0.1:3561
  server and :3562 local, a gateway key, dsh profile web wired to
  office/up/m1). `magpie group add kacli-fast` on the server put
  office/group/kacli-fast in the local cordis.patch.yml in 1.14s
  (log: "office: its list changed there, fetched again: 3 models"). 130s
  idle after it: no further fetch.
  Control: origin/main on both, nothing in 37s. origin/main server, this
  local: nothing in 37s, logged once "doesn't wait ... fetched on its
  schedule", asked once.

Broken by hand, each red:
- Without the dispatch to the wait: TestModelsWaitTagged,
  AnswersAChange, EndsWithTheGateway.
- Without the filememo.Written wake: TestModelsWaitAnswersAChange
  (answered after 5.0s, at the others timer).
- Without RefetchTaking in the follower: TestRemoteMagpieListFollowed.
- Without the RefreshInterval > 0 check: TestRemoteMagpieOffNotFollowed
  (asked 3 times).
- Removing the holdCatalog exemption is caught by no test: a held
  catalog is still dropped on a write (heldFreshLocked), so the change is
  seen. It is kept so a 50s hold doesn't pin the build, as with a
  WebSocket.

Not tried: across two real computers on a LAN, or behind a reverse
proxy (only loopback with a key, and the LAN/no-key, foreign Origin and
Origin null refusals in TestModelsWaitGuardedAsTheList). Not tried on
Windows or Linux. Agents other than dsh weren't checked, though they go
through the same catalog.Touched sync.

Reported-by: KaCli (Discord)
2026-11-06 20:57:55 +08:00

153 lines
4.6 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// listAsk asks srv's list, waiting wait seconds at the list tag names when
// wait is set.
func listAsk(t *testing.T, url, wait, tag string) (int, 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)
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
return res.StatusCode, res.Header.Get("ETag"), string(b)
}
// 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.
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, 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)
}
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 d := time.Since(start); d < 900*time.Millisecond {
t.Errorf("the same list answered after %v, before its wait ended", d)
}
}
// A change saved while another magpie waits answers it the new list at
// once, not at the end of its wait.
func TestModelsWaitAnswersAChange(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
srv := httptest.NewServer(New().Handler())
defer srv.Close()
_, tag, _ := listAsk(t, srv.URL, "1", "")
go func() {
time.Sleep(300 * time.Millisecond)
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.Error(err)
}
}()
start := time.Now()
code, now, body := listAsk(t, srv.URL, "30", tag)
if code != 200 || now == "" || now == tag {
t.Fatalf("after a change: %d, ETag %q (was %q)", code, now, tag)
}
if !strings.Contains(body, "m2") {
t.Errorf("the new list lacks m2: %s", body)
}
if d := time.Since(start); d > 3*time.Second {
t.Errorf("the change answered after %v", d)
}
}
// A gateway stopping ends every wait with 304: the other magpie keeps its
// tag and asks the next gateway.
func TestModelsWaitEndsWithTheGateway(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
s := New()
srv := httptest.NewServer(s.Handler())
defer srv.Close()
_, tag, _ := listAsk(t, srv.URL, "1", "")
go func() {
time.Sleep(200 * time.Millisecond)
s.endStreams()
}()
start := time.Now()
code, _, _ := listAsk(t, srv.URL, "30", tag)
if code != http.StatusNotModified {
t.Fatalf("a wait as the gateway stops: %d, want 304", code)
}
if d := time.Since(start); d > 3*time.Second {
t.Errorf("answered after %v", d)
}
}
// The wait is the list's own route: a caller the list refuses (another
// computer with no key, a foreign page) is refused it the same with the
// header, before anything waits.
func TestModelsWaitGuardedAsTheList(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
setup(t, provider.Chat, &fake{t: t})
newCaller(t, "LAN client")
h := New().Front()
ask := func(remote, origin string, wait bool) (int, string) {
r := httptest.NewRequest("GET", "/v1/models", nil)
r.RemoteAddr = remote
if origin != "" {
r.Header.Set("Origin", origin)
}
if wait {
r.Header.Set(provider.ListWaitHeader, "30")
r.Header.Set("If-None-Match", `"ml-anything"`)
}
w := httptest.NewRecorder()
done := make(chan struct{})
go func() { defer close(done); h.ServeHTTP(w, r) }()
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatalf("%s %s was held", remote, origin)
}
return w.Code, w.Body.String()
}
for _, c := range []struct{ remote, origin string }{
{"192.168.1.9:5000", ""},
{"127.0.0.1:5000", "https://evil.example"},
{"127.0.0.1:5000", "null"},
} {
plain, _ := ask(c.remote, c.origin, false)
if plain == 200 {
t.Fatalf("%s %s: the plain list was answered; the case tests nothing", c.remote, c.origin)
}
waited, body := ask(c.remote, c.origin, true)
if waited != plain {
t.Errorf("%s %s: %d with the wait, %d without (%s)", c.remote, c.origin, waited, plain, body)
}
}
}