Files
magpie/internal/plugin/market_npm_test.go
T
yetone 3a4df527f5 plugin, provider, gateway, upstream: a test whose check fails while its fake vendor holds a reply ends with a FAIL, not a package hung until -timeout (#1808)
TestNPMInfoDeadline's fake npm held slow-one's reply on <-release, closed only
on the happy path. A check firing first under load (on the issue's machine,
the quick ones missing at npmAll = 300ms) left the handler held, and
httptest.Server.Close, run in the test's cleanup, waited for it forever:
the whole internal/plugin package hung to -timeout and lost every result.

- TestNPMInfoDeadline: a t.Cleanup registered after fakeNPM (so it runs
  before the fake's Close) lets the handler go once (sync.OnceFunc). Its
  timing assumptions, all listed: the 2s wall-clock bound on Info is gone
  (slow-one is held and npmEach is an hour, so Info coming back at all is
  npmAll at work; a minute only turns a wait into a FAIL); npmAll is 5s,
  the quick ones' time to answer on a loaded machine, not 300ms; the slow
  one's kept answer is polled for 30s, not 3s.
- The same pattern in its siblings, each fake handler blocked on a channel
  only the happy path closed, now let go by a cleanup/defer that runs
  before the server's Close: TestRestartFinishesTheReply (plugin),
  TestPastedAddressAndCallbackFinishOnce, TestPartnersFetchedLastIsHeld
  (provider), TestBusy (before gw.Close too, whose request waits on it),
  TestLaneReleasedOnFailure (gateway), TestReadOnceInFresh (upstream; its
  100ms bound on Of goes the same way as the 2s one: the page is held, so
  Of coming back is its not waiting, 10s being short of the read's 15s).
- Audited, already right: grok_accounts, quota_refresh_order,
  quota_history_waiter, subscription_usage, sub2api_usage, qoder, routing,
  github_test, session_route, request_encoding, key_limits, vertex (quit),
  plugin_usage (r.Context).

Run, in a sandbox HOME with pinned caches:
- Old TestNPMInfoDeadline with its check forced (took > 0): "httptest.Server
  blocked in Close", panic at -timeout 30s. With a 500ms delay injected into
  the fake's answers (a loaded machine): FAIL at the quick-ones check, then
  the same hang. New test: with the delay injected, PASS (5.55s); with the
  check forced, FAIL in 5.5s and the package's other tests run; with
  npmAll an hour (the deadline broken), "Info waited for the slow package"
  and the package ends.
- Each sibling with t.Fatal injected while its handler is held: old code,
  all five httptest siblings hang to -timeout 90s ("blocked in Close"),
  upstream's stalls ~56s; new code, each ends at once with FAIL.
- go test -race -count=5 of every touched test: pass.
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean, before and after rebasing onto
  a3f2097ed. go test -tags nogui ./... (darwin): all 49 packages ok before
  the rebase; after it, all ok but internal/proc's
  TestFindToolKeepsWrapperWhenMiseDoesntSay/hangs ("mise wasn't asked",
  a 300ms miseWait under load; passes 20 of 20 alone), filed as #1838.
Not run: the Windows box, Linux tests.
2026-10-12 23:24:22 +08:00

186 lines
5.9 KiB
Go

package plugin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// fakeNPM answers as npm's registry and its downloads do, through the
// handler given, for one test.
func fakeNPM(t *testing.T, h http.HandlerFunc) {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
reg, dl, atOnce, each, all := npmRegistry, npmDownloads, npmAtOnce, npmEach, npmAll
npmRegistry, npmDownloads = srv.URL, srv.URL
ReloadInfo()
t.Cleanup(func() {
npmRegistry, npmDownloads, npmAtOnce, npmEach, npmAll = reg, dl, atOnce, each, all
ReloadInfo()
})
}
func npmAnswer(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/downloads/") {
w.Write([]byte(`{"downloads":1234}`))
return
}
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/latest")
w.Write([]byte(`{"version":"1.2.3","description":"` + name + `","_npmUser":{"name":"me"}}`))
}
// What npm said is kept on disk: a magpie started again shows it at once,
// before asking, and when npm is down it is what the page shows.
func TestNPMInfoKeptOnDisk(t *testing.T) {
up := atomic.Bool{}
up.Store(true)
fakeNPM(t, func(w http.ResponseWriter, r *http.Request) {
if !up.Load() {
http.Error(w, "down", 500)
return
}
npmAnswer(w, r)
})
ctx := context.Background()
got := Info(ctx, []string{"opencode-x-auth"})
if n := got["opencode-x-auth"]; n.Version != "1.2.3" || n.Weekly != 1234 || n.Publisher != "me" {
t.Fatalf("asked: %+v", got)
}
// started again: nothing in memory, the disk's copy there without asking
up.Store(false)
ReloadInfo()
if n := InfoCached([]string{"opencode-x-auth", "never-asked"}); n["opencode-x-auth"].Version != "1.2.3" || len(n) != 1 {
t.Fatalf("from disk: %+v", n)
}
// an hour on, npm down: what it said last
npmMu.Lock()
e := npmCached()["opencode-x-auth"]
e.At = time.Now().Add(-2 * time.Hour)
npmCache["opencode-x-auth"] = e
npmMu.Unlock()
if n := Info(ctx, []string{"opencode-x-auth"}); n["opencode-x-auth"].Version != "1.2.3" {
t.Fatalf("npm down: %+v", n)
}
}
// One package npm is slow to answer for doesn't hold the rest: Info
// answers by its deadline, the slow one as it was last (missing, never
// asked before), and its answer, once it comes, is kept for the next ask.
func TestNPMInfoDeadline(t *testing.T) {
release := make(chan struct{})
fakeNPM(t, func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "slow-one") {
<-release
}
npmAnswer(w, r)
})
// registered after fakeNPM, so it runs before the fake's Close, which
// waits for every handler: a check below that fails doesn't leave the
// slow one held and the package hung until -timeout (#1808)
let := sync.OnceFunc(func() { close(release) })
t.Cleanup(let)
// The slow one is held until the test lets it go and each package is
// waited on for an hour, so Info coming back at all is npmAll at work,
// with no wall-clock bound a loaded machine can pass; the minute only
// turns a wait into a FAIL. npmAll is the quick ones' time to answer,
// room enough on a loaded machine.
npmEach, npmAll = time.Hour, 5*time.Second
answered := make(chan map[string]NPM, 1)
go func() { answered <- Info(context.Background(), []string{"fast-one", "slow-one", "fast-two"}) }()
var got map[string]NPM
select {
case got = <-answered:
case <-time.After(time.Minute):
t.Fatal("Info waited for the slow package")
}
if got["fast-one"].Version != "1.2.3" || got["fast-two"].Version != "1.2.3" {
t.Fatalf("the quick ones: %+v", got)
}
if _, ok := got["slow-one"]; ok {
t.Fatalf("the slow one before it answered: %+v", got["slow-one"])
}
let()
deadline := time.Now().Add(30 * time.Second)
for InfoCached([]string{"slow-one"})["slow-one"].Version == "" {
if time.Now().After(deadline) {
t.Fatal("the slow one's answer wasn't kept")
}
time.Sleep(10 * time.Millisecond)
}
}
// npm is asked of a few packages at a time, not of all of them at once.
func TestNPMInfoAtOnce(t *testing.T) {
var mu sync.Mutex
now, most := 0, 0
fakeNPM(t, func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/downloads/") {
npmAnswer(w, r)
return
}
mu.Lock()
now++
most = max(most, now)
mu.Unlock()
time.Sleep(40 * time.Millisecond)
mu.Lock()
now--
mu.Unlock()
npmAnswer(w, r)
})
npmAtOnce = 3
names := []string{}
for i := range 12 {
names = append(names, "pkg-"+string(rune('a'+i)))
}
names = append(names, "not a name", "pkg-a")
got := Info(context.Background(), names)
if len(got) != 12 {
t.Fatalf("%d answered, want 12: %+v", len(got), got)
}
if most > 3 || most == 0 {
t.Fatalf("%d asked at once, want at most 3", most)
}
}
// yetone: 这里的 agent plugin 为什么没有 logo. The picture a package gives
// in package.json's magpie.icon comes with what npm says of it, so a
// listing the market gives no icon shows it; anything but an https URL or
// a data:image URI is left out.
func TestNPMInfoGivesIcon(t *testing.T) {
icons := map[string]string{
"agent-aider": "data:image/png;base64,iVBORw0KGgo=",
"agent-web": "https://aider.chat/icon.png",
"agent-plain": "http://aider.chat/icon.png",
"agent-js": "javascript:alert(1)",
"agent-none": "",
}
fakeNPM(t, func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/downloads/") {
w.Write([]byte(`{"downloads":1}`))
return
}
name := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/latest")
w.Write([]byte(`{"version":"0.1.1","magpie":{"agent":"./a.agent.js","icon":"` + icons[name] + `"}}`))
})
names := []string{}
for n := range icons {
names = append(names, n)
}
got := Info(context.Background(), names)
want := map[string]string{"agent-aider": icons["agent-aider"], "agent-web": icons["agent-web"]}
for _, n := range names {
if got[n].Version != "0.1.1" || got[n].Icon != want[n] {
t.Errorf("%s: %+v, want icon %q", n, got[n], want[n])
}
}
}