From 30de93e9e9d5bf6a013b1773010700d8eaa707f0 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 20:35:37 +0800 Subject: [PATCH] plugins: a request whose Bun is still downloading fails at once and fails over (#6735) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit hixonchan (kyrierekkok123-del on GitHub): with magpie's own Bun missing and its download stalled, every plugin-served request hung with zero bytes, nothing in the log, no timeout and no failover, and `magpie plugin` hung too. The host's lock (hostMu) was held across Bun's download, which had no bound on the whole, so every caller waited on it whatever its context said. Now: - Bun is downloaded in the background, once at a time per Bun (bunready.go). The host waits for it up to 10s from when it began (bunReadyWait); then each call ends with BunNotReadyError, "Bun runtime not ready: downloading Bun 1.4.2 (12s so far)…" or "… failed: ", logged, and the gateway goes on to the group's next member. - A failed download is said at once for a minute, then tried again; installs (plugin.Bun) still wait as long as their context lets. - hostMu is a channel lock that a caller's context can end (LockCtx); the gateway's TryLock polling loops use it. - When the download fails, a Bun on PATH or in ~/.bun/bin is taken if magpie would run it itself: at least BunVersion, not set aside, passing the try a new release gets. It is copied in as magpie-bun (#1048). magpie's checksummed build stays first; the user's own Bun is better than no plugins, and it is what the reporter fell back on by hand. - Each stage is logged: download started, failed after N, downloaded in N, the PATH Bun taken or refused and why. - Every route through the host gets it: fetch, loader options, sign-in, the plugin listing (CLI and GUI). `magpie plugin` prints the list and the not-ready reason within ~10s. Self-restart and env (the reporter's point 4): Reexec, RelaunchBinary and StartBeside pass os.Environ; only the Mac's bundle relaunch (open -n) starts with LaunchServices' env. Filed as #6757, not changed here. With this change MAGPIE_BUN isn't needed. Tests (each red on the old code with a shim for the new test hooks, logs kept): - TestHostWhileBunDownloadStalls: old code, "a caller whose context ended still waits on the stalled Bun download"; now not-ready at 2s, the 100ms caller returns, then the host starts on the download, asked once. - TestHostAfterBunDownloadFailedSaysWhy: old code, a plain 500 error, not BunNotReady; now the 500 is said twice with one ask, Bun() retries. - TestBunOnPathAfterDownloadFailed: old code failed; now 1.4.2 taken, 1.0.0 refused. - TestPluginWhoseBunIsNotReadyFailsOver (gateway, real Handler): old code, "group/mixed still unanswered after 20s"; now 200 from the next member in 0.84s, and the plugin's own model answers 502 "Bun runtime not ready" after ~300ms. Run on mote at 923cc8747 + this commit (rebased since onto d7cda856a, a GUI-only library change): gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok. go test -tags nogui -count=1 -timeout 45m ./...: every package ok (plugin 219s, gateway 1001s) except two untouched by this change: - internal/usage TestWholeKeptAcrossReset: red on origin/main d7cda856a too, 4 of 5 at -count=5 (#6760). - internal/provider TestRemoveListedAccountLeavesHiddenNamesake: red once in the full run, 5 of 5 alone (#6761). The four new tests pass on Linux (WSL magpie-desktop) and, the two that run there, on Windows (xiaomi-gpu). Not tried: a real magpie binary with a really blocked GitHub download (the gateway test runs the real handler with a stalled release server), and the Mac relaunch. --- docs/subsystems/provider-plugins.md | 2 + internal/gateway/plugin_bunready_test.go | 106 ++++++++ internal/plugin/bun.go | 23 +- internal/plugin/bunready.go | 332 +++++++++++++++++++++++ internal/plugin/bunready_test.go | 239 ++++++++++++++++ internal/plugin/bunupdate_test.go | 8 +- internal/plugin/gateway.go | 20 +- internal/plugin/host.go | 44 ++- internal/plugin/providers.go | 2 + 9 files changed, 746 insertions(+), 30 deletions(-) create mode 100644 internal/gateway/plugin_bunready_test.go create mode 100644 internal/plugin/bunready.go create mode 100644 internal/plugin/bunready_test.go diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index ee578bc39..407adc046 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -311,6 +311,8 @@ A plugin's fetch is followed through a redirect with its headers only to its own magpie downloads the Bun build for this machine (`bunTarget` in [`bun.go`](../../internal/plugin/bun.go)): the baseline build on x64 Linux and Windows, the native `bun-windows-aarch64` on Windows on ARM (it was turned away as having no build until #2183), and on a musl Linux such as Alpine (`libc.Musl`, the check Claude Code's download uses too) the musl one, `bun-linux-x64-musl-baseline` or `bun-linux-aarch64-musl`. A glibc build names glibc's loader, which Alpine lacks, so it couldn't start there and exec said "no such file or directory" (#1877). A musl Linux keeps its Buns and their `state.json` under `bun/musl`, so a machine whose C library changed never runs the other one's build or takes its set-aside versions; everywhere else they stay in `bun`, where a Bun downloaded before is. A bun that is on disk but can't be started says it is a build for another C library and names `MAGPIE_BUN` (`cantStart`), and it isn't fallen back from or set aside: the version before is the same build. Bun's musl build needs libstdc++ and libgcc; on an Alpine without them, `bun add` and the host's start say which library is missing and `apk add libstdc++ libgcc` (`missingLibs`). `TestBunTargetForMusl`, `TestMuslBunKeptApartFromGlibc`, `TestCantStartSaysCLibrary`, `TestHostOnUnstartableBunSaysCLibrary`, `TestMissingLibsNamesThem` and `TestHostOnBunLackingLibsSaysWhich` in [`bunmusl_test.go`](../../internal/plugin/bunmusl_test.go) cover these. +The first time a plugin is asked for, magpie downloads its Bun, and a download on a slow or blocked link can take minutes, stalling up to `downloadStall` (60s) at a time with no bound on the whole (#5572). The host's start used to wait on it while it held the host's lock, so every plugin request, the hooks and `magpie plugin` waited behind it with no bytes, no log line and no failover (#6735, kyrierekkok123-del, v0.1.4259). The download now runs in the background ([`bunready.go`](../../internal/plugin/bunready.go)), one at a time per Bun (`fetchBun`), with log lines when it starts, ends and fails. The host's start (`hostBun`) waits for it until `bunReadyWait` (10s) from when it began, or until the caller's context ends, and then the call fails with a `*BunNotReadyError`: "Bun runtime not ready: downloading Bun 1.4.2 (Ns so far)", or "… failed: ". A gateway request takes it as any member that can't answer (a 502 naming it, or the routing group's next member), and the download goes on. A failed download is said at once for `bunRetryGap` (1 min), then tried again. The host's lock is a `hostLock` that a caller stops waiting for when its context ends (`LockCtx`), so a request is never held past its own deadline behind a start. Installs (`Bun`) still wait for the download, as long as their context lets, and try a failed one again. When the download fails, a Bun on PATH or in `~/.bun/bin` is taken if it is one magpie would run itself (`bunFromPath`: no older than `BunVersion`, not set aside, passing `tryBun`), copied in as magpie-bun, and made the one in use when it is newer. magpie's checksummed build stays the default; only when that can't be had is the user's own Bun used. `TestHostWhileBunDownloadStalls`, `TestHostAfterBunDownloadFailedSaysWhy` and `TestBunOnPathAfterDownloadFailed` in [`bunready_test.go`](../../internal/plugin/bunready_test.go) and `TestPluginWhoseBunIsNotReadyFailsOver` in internal/gateway cover these. + A bun this machine can't run at all says so instead of its exit status (`wontLoad`, a `*BunUnstartableError`). Windows refuses to load Bun 1.3.14 and later before Windows 10 1809 and Windows Server 2019: they import kernel32's `CreatePseudoConsole`, which older Windows lacks, so the process ends with 0xc0000139 (STATUS_ENTRYPOINT_NOT_FOUND) before it runs (zgcwkj on Discord, a Windows service). A processor without an instruction Bun's x64 build uses (it targets SSE4.2) ends it with 0xc000001d on Windows and SIGILL elsewhere. `bun add`, `bun update` and the host's start (`whyDied`, `cantStart`) each wrap the exit in it. The message says which of the two it is and names `MAGPIE_BUN`. An install doesn't try the community repo's dist branch after it, because that `bun add` can't start either. The GUI's `fail` answers it with code `bun_unstartable`, `bunWhy` (`windows` or `cpu`) and `said`, the i18n.js key for it (`bunSaid` in api.go, kept there so app.js holds one line under its budget), which `api()` in app.js puts through `t()` in place of the English. `TestBunSaidIsTranslated` fails when a language lacks it. There is no fallback to an older Bun: the last one Windows Server 2016 loads, 1.3.13, is below `BunVersion`, and Bun's baseline assets are now the same binary. `TestWontLoadSaysWindowsOrCPU`, `TestInstallOnUnstartableBunSaysWhyAndSkipsDist` and `TestHostOnUnstartableBunSaysWhy` in [`bunload_test.go`](../../internal/plugin/bunload_test.go), `TestFailSaysBunUnstartable` in internal/gui and `plugin-bun-unstartable.test.cjs` (both engines, every language) cover these. Plugin downloads can take a proxy of their own, Settings › Network › Plugin downloads (`settings.PluginProxy`, `magpie settings set pluginProxy `; JonahFu on X: GitHub reached only through a proxy, the vendors without). It covers the plugins list, npm's registry and a registry of the user's, GitHub, the dist branch and Bun's own download (`netproxy.Downloads` in `fetchJSONFrom`, `fetchRegistry` and `getURLFrom`), and `bun add`, `bun update`, `bun remove` and git (`dlEnv`, `netproxy.EnvDownloads`). Unset, it follows the global proxy, as every download did before. The host (`bun run`) keeps magpie's own: a plugin's requests to its vendor are API requests. `TestPluginDownloadsTakeTheirOwnProxy` holds both sides. diff --git a/internal/gateway/plugin_bunready_test.go b/internal/gateway/plugin_bunready_test.go new file mode 100644 index 000000000..1b07e3ff6 --- /dev/null +++ b/internal/gateway/plugin_bunready_test.go @@ -0,0 +1,106 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// A plugin's provider whose Bun is still downloading, the download +// stalled, fails at once and says why, and a routing group goes on to its +// next member, as for any other member that can't answer (#6735): neither +// waits on the download. +func TestPluginWhoseBunIsNotReadyFailsOver(t *testing.T) { + bun := testenv.Bun(t) + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + + up := testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from plugin"},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + defer up.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": "a"}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + other := &keyed{} + serveOn(t, "other", "ko", []string{"m"}, other) + if err := provider.SaveGroup(provider.Group{Name: "Mixed", Members: []string{"fakeco/fake-1", "other/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + + // now no Bun on hand: magpie's own is to be downloaded, from a release + // that never answers + stalled := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-stalled: + case <-r.Context().Done(): + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(stalled) }) + t.Cleanup(plugin.BunReleaseForTest(srv.URL, 300*time.Millisecond)) + t.Setenv("MAGPIE_BUN", "") + plugin.Restart() + + s := New() + ask := func(model string) (int, string) { + t.Helper() + type reply struct { + code int + body string + } + got := make(chan reply, 1) + go func() { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hello"}]}`)) + s.Handler().ServeHTTP(rec, req) + got <- reply{rec.Code, rec.Body.String()} + }() + select { + case r := <-got: + return r.code, r.body + case <-time.After(20 * time.Second): + close(stalled) + stalled = make(chan struct{}) + t.Fatalf("%s still unanswered after 20s while Bun downloads", model) + return 0, "" + } + } + if code, body := ask("group/mixed"); code != 200 || !strings.Contains(body, "from ko") { + t.Fatalf("the group with its plugin member's Bun not ready: %d %s", code, body) + } + if code, body := ask("fakeco/fake-1"); code < 500 || !strings.Contains(body, "Bun runtime not ready") { + t.Fatalf("the plugin's model with its Bun not ready: %d %s", code, body) + } +} diff --git a/internal/plugin/bun.go b/internal/plugin/bun.go index 5be1f08a2..366c60030 100644 --- a/internal/plugin/bun.go +++ b/internal/plugin/bun.go @@ -242,22 +242,27 @@ func wontLoad(bun string, err error) *BunUnstartableError { // Bun is the bun to run plugins with: $MAGPIE_BUN when set, else the one // magpie downloaded and keeps up to date, downloading it now when there -// is none yet. +// is none yet (tried again when a download failed before), for as long as +// ctx lets it wait. The download goes on in the background when ctx ends +// first (bunready.go); the plugin host asks hostBun, which waits less. func Bun(ctx context.Context) (string, error) { if b := os.Getenv("MAGPIE_BUN"); b != "" { return b, nil } - bunMu.Lock() - defer bunMu.Unlock() - v := inUseLocked() - exe := bunExeOf(v) - if haveBun(v) { + v, exe, ok := bunAtHand() + if ok { return exe, nil } - if err := downloadBun(ctx, v, exe); err != nil { - return "", fmt.Errorf("downloading Bun %s to run plugins: %w", v, err) + f := fetchBun(v, exe, true) + select { + case <-f.done: + if f.err != nil { + return "", fmt.Errorf("downloading Bun %s to run plugins: %w", v, f.err) + } + return f.got, nil + case <-ctx.Done(): + return "", f.notReady(ctx.Err()) } - return exe, nil } // HasBun is whether a Bun is at hand without a download. diff --git a/internal/plugin/bunready.go b/internal/plugin/bunready.go new file mode 100644 index 000000000..8103f4469 --- /dev/null +++ b/internal/plugin/bunready.go @@ -0,0 +1,332 @@ +package plugin + +// Bun while it is being downloaded (#6735). magpie downloads its Bun the +// first time a plugin is asked for, and a download on a slow or blocked +// link can take minutes, or stall a minute at a time and go on. A request +// for a plugin's provider used to wait on it, holding the host's lock, so +// every other request waited behind it: zero bytes, nothing in the log, +// and a routing group never went on to its next member. +// +// The download now runs in the background, once at a time for each Bun. +// The host waits for it a short while (bunReadyWait from when it began), +// then each call for the host ends with a BunNotReadyError that says how +// far it is, or why it failed, and the gateway goes on to the next member. +// A failed download is said at once for bunRetryGap, then tried again by +// the next call. Installs (Bun) wait for it as long as their context lets. +// +// When the download fails, a Bun on PATH is taken if it is one magpie +// would run itself: no older than BunVersion, not set aside, passing the +// try a new release gets. magpie's checksummed build stays the one used +// whenever it can be had; the user's own Bun is better than no plugins. + +import ( + "context" + "fmt" + "io" + "log" + "os" + "os/exec" + "path/filepath" + "sync" + "time" +) + +// BunNotReadyError is a call for the plugin host while the Bun it runs on +// is still downloading, or after its download failed. +type BunNotReadyError struct { + Version string + // For is how long the download has gone on, while it goes on. + For time.Duration + // Err is why the download failed; nil while it goes on. + Err error + // ctx is the caller's context's error, when it ended the wait. + ctx error +} + +func (e *BunNotReadyError) Error() string { + if e.Err != nil { + return fmt.Sprintf("Bun runtime not ready: downloading Bun %s failed: %v", e.Version, e.Err) + } + d := e.For.Round(time.Second) + if d == 0 { + d = e.For.Round(100 * time.Millisecond) + } + return fmt.Sprintf("Bun runtime not ready: downloading Bun %s (%s so far); plugins run once it is done", e.Version, d) +} + +func (e *BunNotReadyError) Unwrap() []error { + var out []error + for _, err := range []error{e.Err, e.ctx} { + if err != nil { + out = append(out, err) + } + } + return out +} + +var ( + // bunReadyWait is how long the host waits on a download from when it + // began before calls for it are told Bun isn't ready. A var for tests. + bunReadyWait = 10 * time.Second + // bunRetryGap is how long a failed download is said to the host's + // callers before one of them tries it again. + bunRetryGap = time.Minute + // bunSayGap throttles the log line of calls told Bun isn't ready. + bunSayGap = 30 * time.Second +) + +// pathBuns are the Buns on this machine to fall back on: the one on PATH, +// and the one Bun's installer puts in ~/.bun/bin, which an app started +// from the Dock or Finder doesn't have on PATH. A var for tests. +var pathBuns = func() []string { + var out []string + if p, err := exec.LookPath(bunExe()); err == nil { + out = append(out, p) + } + if h, err := os.UserHomeDir(); err == nil { + out = append(out, filepath.Join(h, ".bun", "bin", bunExe())) + } + return out +} + +// bunFetch is one download of a Bun, run in the background. +type bunFetch struct { + v, exe string + started time.Time + cancel context.CancelFunc + done chan struct{} + // set before done is closed + got string // the Bun the fetch gave + err error + ended time.Time +} + +var bunFetches struct { + sync.Mutex + last map[string]*bunFetch // by where the Bun goes + going map[*bunFetch]bool + wg sync.WaitGroup + said time.Time +} + +// bunAtHand is the Bun plugins run on and whether it is on disk. +func bunAtHand() (v, exe string, ok bool) { + bunMu.Lock() + defer bunMu.Unlock() + v = inUseLocked() + exe = bunExeOf(v) + return v, exe, haveBun(v) +} + +// fetchBun is the download of Bun v to exe: the one going, else the one +// that failed less than bunRetryGap ago unless again, else a new one. +func fetchBun(v, exe string, again bool) *bunFetch { + bunFetches.Lock() + defer bunFetches.Unlock() + if f := bunFetches.last[exe]; f != nil { + select { + case <-f.done: + if f.err != nil && !again && time.Since(f.ended) < bunRetryGap { + return f + } + default: + return f + } + } + ctx, cancel := context.WithCancel(context.Background()) + f := &bunFetch{v: v, exe: exe, started: time.Now(), cancel: cancel, done: make(chan struct{})} + if bunFetches.last == nil { + bunFetches.last = map[string]*bunFetch{} + } + if bunFetches.going == nil { + bunFetches.going = map[*bunFetch]bool{} + } + bunFetches.last[exe] = f + bunFetches.going[f] = true + bunFetches.wg.Add(1) + go f.run(ctx) + return f +} + +func (f *bunFetch) run(ctx context.Context) { + defer bunFetches.wg.Done() + defer f.cancel() + log.Printf("plugins: Bun runtime not ready: downloading Bun %s to %s", f.v, f.exe) + got, err := f.exe, downloadBun(ctx, f.v, f.exe) + if err != nil && ctx.Err() == nil { + log.Printf("plugins: downloading Bun %s failed after %s: %v", f.v, time.Since(f.started).Round(time.Second), err) + if p, ok := bunFromPath(ctx); ok { + got, err = p, nil + } + } else if err == nil { + log.Printf("plugins: Bun %s downloaded in %s", f.v, time.Since(f.started).Round(time.Second)) + } + bunFetches.Lock() + delete(bunFetches.going, f) + bunFetches.Unlock() + f.got, f.err, f.ended = got, err, time.Now() + close(f.done) +} + +// notReady is the error a caller is given while f goes on or after it +// failed; cause is the caller's context's error, if it ended the wait. +func (f *bunFetch) notReady(cause error) *BunNotReadyError { + e := &BunNotReadyError{Version: f.v, ctx: cause} + select { + case <-f.done: + e.Err = f.err + default: + e.For = time.Since(f.started) + } + return e +} + +// hostBun is the Bun to start the host on. While it is downloading, the +// wait is bounded by ctx and by bunReadyWait from when the download began; +// past them the caller is told Bun isn't ready, and the download goes on. +func hostBun(ctx context.Context) (string, error) { + if b := os.Getenv("MAGPIE_BUN"); b != "" { + return b, nil + } + v, exe, ok := bunAtHand() + if ok { + return exe, nil + } + f := fetchBun(v, exe, false) + wait := time.NewTimer(time.Until(f.started.Add(bunReadyWait))) + defer wait.Stop() + select { + case <-f.done: + if f.err == nil { + return f.got, nil + } + case <-ctx.Done(): + case <-wait.C: + } + e := f.notReady(ctx.Err()) + bunFetches.Lock() + say := time.Since(bunFetches.said) >= bunSayGap + if say { + bunFetches.said = time.Now() + } + bunFetches.Unlock() + if say { + log.Printf("plugins: a call for the plugin host ended: %v", e) + } + return "", e +} + +// bunNotReadyNow is why a caller who stopped waiting for the host (cause) +// got no host, when that is Bun's download: nil when Bun is at hand. +func bunNotReadyNow(cause error) error { + if os.Getenv("MAGPIE_BUN") != "" { + return nil + } + _, exe, ok := bunAtHand() + if ok { + return nil + } + bunFetches.Lock() + f := bunFetches.last[exe] + bunFetches.Unlock() + if f == nil { + return nil + } + return f.notReady(cause) +} + +// bunFromPath is a Bun on this machine taken when magpie's own download +// failed, copied in where magpie keeps that version, as magpie-bun +// (#1048), and made the one in use when it is newer than BunVersion. +func bunFromPath(ctx context.Context) (string, bool) { + seen := map[string]bool{} + for _, p := range pathBuns() { + if real, err := filepath.EvalSymlinks(p); err != nil || seen[real] { + continue + } else { + seen[real] = true + } + rv := bunReported(p) + bunMu.Lock() + ok := bunVersionRe.MatchString(rv) && readBunState().usable(rv) + bunMu.Unlock() + if !ok { + log.Printf("plugins: the Bun at %s (%q) isn't one magpie runs: at least %s, not set aside", p, rv, BunVersion) + continue + } + if err := tryBun(ctx, p, rv); err != nil { + log.Printf("plugins: the Bun at %s failed its try: %v", p, err) + continue + } + exe := bunExeOf(rv) + if err := copyBun(p, exe); err != nil { + log.Printf("plugins: taking the Bun at %s: %v", p, err) + continue + } + bunMu.Lock() + s := readBunState() + var err error + if rv != BunVersion && s.Current != rv { + s.Current = rv + err = writeBunState(s) + } + bunMu.Unlock() + if err != nil { + log.Printf("plugins: taking the Bun at %s: %v", p, err) + continue + } + log.Printf("plugins: running plugins on Bun %s from %s", rv, p) + return exe, true + } + return "", false +} + +func copyBun(from, to string) error { + in, err := os.Open(from) + if err != nil { + return err + } + defer in.Close() + if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil { + return err + } + tmp := to + ".part" + out, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + os.Remove(tmp) + return err + } + if err := out.Close(); err != nil { + os.Remove(tmp) + return err + } + return os.Rename(tmp, to) +} + +// endBunFetches stops the downloads going and forgets the ones done: for +// Settle, as a download writes in the test's folder. +func endBunFetches() { + bunFetches.Lock() + for f := range bunFetches.going { + f.cancel() + } + bunFetches.last = nil + bunFetches.Unlock() + bunFetches.wg.Wait() +} + +// BunReleaseForTest has Bun downloaded from url, the host waiting wait +// for it, and no Bun on PATH taken, until restore. +func BunReleaseForTest(url string, wait time.Duration) (restore func()) { + oldURL, oldWait, oldPath := bunRelease, bunReadyWait, pathBuns + bunRelease, bunReadyWait = url, wait + pathBuns = func() []string { return nil } + return func() { + endBunFetches() + bunRelease, bunReadyWait, pathBuns = oldURL, oldWait, oldPath + } +} diff --git a/internal/plugin/bunready_test.go b/internal/plugin/bunready_test.go new file mode 100644 index 000000000..7f8f94cc8 --- /dev/null +++ b/internal/plugin/bunready_test.go @@ -0,0 +1,239 @@ +package plugin + +import ( + "archive/zip" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/testenv" +) + +// heldBunReleases serves a Bun release whose zip (holding exe) is held +// back until gate is closed, as a download that stalls on a slow or +// blocked link is (#6735); fail answers it with a 500 instead. +func heldBunReleases(t *testing.T, exe []byte, gate <-chan struct{}, fail bool) *atomic.Int32 { + t.Helper() + target, err := bunTarget() + if err != nil { + t.Skip(err) + } + var zb bytes.Buffer + zw := zip.NewWriter(&zb) + h := &zip.FileHeader{Name: target + "/" + bunExe(), Method: zip.Deflate} + h.SetMode(0o755) + w, _ := zw.CreateHeader(h) + w.Write(exe) + zw.Close() + sum := sha256.Sum256(zb.Bytes()) + oldSum, hadSum := bunSums[target+".zip"] + bunSums[target+".zip"] = hex.EncodeToString(sum[:]) + t.Cleanup(func() { + if hadSum { + bunSums[target+".zip"] = oldSum + } else { + delete(bunSums, target+".zip") + } + }) + var asked atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/"+target+".zip") { + http.NotFound(w, r) + return + } + asked.Add(1) + if fail { + http.Error(w, "no", http.StatusInternalServerError) + return + } + select { + case <-gate: + w.Write(zb.Bytes()) + case <-r.Context().Done(): + } + })) + // the download is let go before the server waits for its requests + t.Cleanup(srv.Close) + t.Cleanup(Settle) + old := bunRelease + bunRelease = srv.URL + t.Cleanup(func() { bunRelease = old }) + return &asked +} + +func readyWait(t *testing.T, d time.Duration) { + old := bunReadyWait + bunReadyWait = d + t.Cleanup(func() { bunReadyWait = old }) +} + +func waitWithin(t *testing.T, what string, within time.Duration, ok func() bool) { + t.Helper() + end := time.Now().Add(within) + for !ok() { + if time.Now().After(end) { + t.Fatalf("no %s within %s", what, within) + } + time.Sleep(10 * time.Millisecond) + } +} + +// While the Bun to run plugins is still downloading, a call for the host +// ends with why instead of waiting on the download (#6735): within the +// bounded wait, or at once when the caller's own context ends first, +// another caller holding the host's lock or not. The download goes on in +// the background, once, and the host starts on it when it is done. +func TestHostWhileBunDownloadStalls(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the downloaded bun is a shell script") + } + real := testenv.Bun(t) + bunHome(t, BunVersion, time.Now()) + gate := make(chan struct{}) + opened := false + open := func() { + if !opened { + opened = true + close(gate) + } + } + t.Cleanup(open) + asked := heldBunReleases(t, []byte("#!/bin/sh\nexec "+real+" \"$@\"\n"), gate, false) + readyWait(t, 2*time.Second) + + ctx := context.Background() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + + first := make(chan error, 1) + began := time.Now() + go func() { _, err := Plugins(ctx); first <- err }() + waitWithin(t, "download asked for", 10*time.Second, func() bool { return asked.Load() >= 1 }) + + // a caller whose context ends while another waits on the host + short, cancel := context.WithTimeout(ctx, 100*time.Millisecond) + defer cancel() + second := make(chan error, 1) + go func() { _, err := Plugins(short); second <- err }() + select { + case err := <-second: + if err == nil { + t.Fatal("Plugins answered with no Bun") + } + case <-time.After(10 * time.Second): + open() + t.Fatal("a caller whose context ended still waits on the stalled Bun download") + } + + select { + case err := <-first: + var nr *BunNotReadyError + if !errors.As(err, &nr) || !strings.Contains(err.Error(), "Bun runtime not ready") || !strings.Contains(err.Error(), "downloading Bun "+BunVersion) { + t.Fatalf("Plugins = %v, want Bun runtime not ready", err) + } + if d := time.Since(began); d > 10*time.Second { + t.Fatalf("Plugins took %s", d) + } + case <-time.After(15 * time.Second): + open() + t.Fatal("Plugins still waits on the stalled Bun download after 15s") + } + + // the download went on, once, and the host starts on it + open() + waitWithin(t, "Bun downloaded", 30*time.Second, HasBun) + lctx, lcancel := context.WithTimeout(ctx, time.Minute) + defer lcancel() + ls, err := Plugins(lctx) + if err != nil || len(ls) != 1 { + t.Fatalf("Plugins = %+v, %v once Bun is here", ls, err) + } + if n := asked.Load(); n != 1 { + t.Fatalf("Bun downloaded %d times", n) + } +} + +// A download that failed is said at once to the next call for the host, +// not tried again by every request; an install (Bun) tries it again. +func TestHostAfterBunDownloadFailedSaysWhy(t *testing.T) { + bunHome(t, BunVersion, time.Now()) + asked := heldBunReleases(t, []byte("bun"), nil, true) + readyWait(t, 10*time.Second) + ctx := context.Background() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + for i := range 2 { + began := time.Now() + _, err := Plugins(ctx) + var nr *BunNotReadyError + if !errors.As(err, &nr) || !strings.Contains(err.Error(), "failed") || !strings.Contains(err.Error(), "500") { + t.Fatalf("Plugins #%d = %v, want the download's failure", i+1, err) + } + if d := time.Since(began); d > 5*time.Second { + t.Fatalf("Plugins #%d took %s", i+1, d) + } + } + if n := asked.Load(); n != 1 { + t.Fatalf("the failed download was tried %d times by the host", n) + } + if _, err := Bun(ctx); err == nil || asked.Load() != 2 { + t.Fatalf("Bun = %v after %d downloads, want a second try", err, asked.Load()) + } +} + +// When the download fails, a Bun on PATH is taken when it is one magpie +// would run (at least BunVersion, not set aside, passing its try), copied +// in as magpie-bun; an older one is not. +func TestBunOnPathAfterDownloadFailed(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the bun on PATH is a shell script") + } + for _, c := range []struct { + says string + take bool + }{{BunVersion, true}, {"1.0.0", false}} { + t.Run(c.says, func(t *testing.T) { + bunHome(t, BunVersion, time.Now()) + heldBunReleases(t, []byte("bun"), nil, true) + onPath := filepath.Join(t.TempDir(), "bun") + testenv.Program(t, onPath, "#!/bin/sh\necho "+c.says+"\n") + pathBunsAre(t, onPath) + stubTry(t, func(exe, v string) error { return nil }) + exe, err := Bun(context.Background()) + if !c.take { + if err == nil { + t.Fatalf("Bun %s on PATH taken: %s", c.says, exe) + } + return + } + if err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(exe) + if exe != bunExeOf(c.says) || !strings.Contains(string(b), "echo "+c.says) { + t.Fatalf("Bun = %s holding %q", exe, b) + } + }) + } +} + +func pathBunsAre(t *testing.T, buns ...string) { + old := pathBuns + pathBuns = func() []string { return buns } + t.Cleanup(func() { pathBuns = old }) +} diff --git a/internal/plugin/bunupdate_test.go b/internal/plugin/bunupdate_test.go index a8528999e..cb4ac27fe 100644 --- a/internal/plugin/bunupdate_test.go +++ b/internal/plugin/bunupdate_test.go @@ -67,8 +67,8 @@ func bunReleases(t *testing.T, exe []byte) *atomic.Int32 { return &asked } -// bunHome gives the test its own magpie folders, no $MAGPIE_BUN, and Bun's -// newest release as given. +// bunHome gives the test its own magpie folders, no $MAGPIE_BUN, no Bun +// on PATH taken, and Bun's newest release as given. func bunHome(t *testing.T, latest string, published time.Time) { t.Helper() dir := t.TempDir() @@ -81,6 +81,10 @@ func bunHome(t *testing.T, latest string, published time.Time) { old := bunLatest bunLatest = func(context.Context) (string, time.Time, error) { return latest, published, nil } t.Cleanup(func() { bunLatest = old }) + // nor a Bun on the machine's PATH to fall back on + oldPath := pathBuns + pathBuns = func() []string { return nil } + t.Cleanup(func() { pathBuns = oldPath }) } func stubTry(t *testing.T, f func(exe, v string) error) { diff --git a/internal/plugin/gateway.go b/internal/plugin/gateway.go index c6f9a67fa..e32dcfe0e 100644 --- a/internal/plugin/gateway.go +++ b/internal/plugin/gateway.go @@ -247,14 +247,8 @@ func GatewayBegin(ctx context.Context, body []byte, info GatewayContext) *Gatewa checkList() // Provider discovery may already be starting the shared host. Wait within // the same hook budget rather than skipping recall on the first request. - wait := time.NewTicker(10 * time.Millisecond) - defer wait.Stop() - for !hostMu.TryLock() { - select { - case <-start.Done(): - return nil - case <-wait.C: - } + if hostMu.LockCtx(start) != nil { + return nil } if start.Err() != nil { hostMu.Unlock() @@ -355,14 +349,8 @@ func GatewaySignIn(ctx context.Context, ev SignInEvent) { start, cancelStart := context.WithTimeout(ctx, gatewayStart) defer cancelStart() checkList() - wait := time.NewTicker(10 * time.Millisecond) - defer wait.Stop() - for !hostMu.TryLock() { - select { - case <-start.Done(): - return - case <-wait.C: - } + if hostMu.LockCtx(start) != nil { + return } h, err := getLocked(start) hostMu.Unlock() diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 6fcfde067..b38e045ef 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -667,8 +667,41 @@ func Clashes(loaded []Loaded) map[string][]Clash { return out } +// hostLock is a lock a caller stops waiting for when its context ends: a +// host starting holds it while its Bun downloads (bunReadyWait at most), +// and a request is not held past its own deadline behind that (#6735). +type hostLock chan struct{} + +func (l hostLock) Lock() { l <- struct{}{} } + +func (l hostLock) TryLock() bool { + select { + case l <- struct{}{}: + return true + default: + return false + } +} + +func (l hostLock) LockCtx(ctx context.Context) error { + select { + case l <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (l hostLock) Unlock() { + select { + case <-l: + default: + panic("plugin: unlock of unlocked hostMu") + } +} + var ( - hostMu sync.Mutex + hostMu = make(hostLock, 1) current *host // generation counts the hosts started, so a caller can tell a // restart happened (the provider cache is then stale) @@ -970,7 +1003,12 @@ func hostScript(name string, js []byte) (string, error) { // when there is none. func get(ctx context.Context) (*host, error) { checkList() - hostMu.Lock() + if err := hostMu.LockCtx(ctx); err != nil { + if e := bunNotReadyNow(err); e != nil { + return nil, e + } + return nil, fmt.Errorf("waiting for the plugin host: %w", err) + } defer hostMu.Unlock() return getLocked(ctx) } @@ -998,7 +1036,7 @@ func getLocked(ctx context.Context) (*host, error) { } func start(ctx context.Context) (*host, error) { - bun, err := Bun(ctx) + bun, err := hostBun(ctx) if err != nil { return nil, err } diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 8c0123009..ca7b5c86a 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -697,6 +697,8 @@ func Settle() { // answered with these UseCached(nil) cancelCatalogSyncs() + // nor a Bun download, which writes in the test's folder + endBunFetches() } // Cached is the plugins' providers as last asked, without starting the