diff --git a/internal/plugin/dist.go b/internal/plugin/dist.go index 002da8353..2f1aa6e4c 100644 --- a/internal/plugin/dist.go +++ b/internal/plugin/dist.go @@ -61,40 +61,89 @@ var ( distIdx *distIndex distAt time.Time // when distIdx was read, or last failed to be distOK bool // whether the last read was distIdx's + distErr error // why the last read failed, when it did distKeep = 10 * time.Minute distWait = time.Minute // after a read failed, before asking again + // distReading is closed when the read under way ends, nil when none is + distReading chan struct{} + // distReadFor is how long a read of the index is given: its own + // time, not one package's ask's. index.json is ~1.6MB, which a slow + // link took longer than npmEach's 6s to bring, and a read cut off + // there said the branch had nothing (ferock on Discord: the Chat + // page plugin, on the dist branch only, showed Coming soon). A read + // that ends after its asker stopped waiting is kept for the next ask. + distReadFor = 2 * time.Minute ) +// errDistUnread is a package the dist branch may have, unknown for the +// branch not having been read. +var errDistUnread = errors.New("the community repo's dist branch can't be read") + // distFile is a file the index may name: one tarball under tgz/, nothing // that leaves the branch or plugins/dist. var distFile = regexp.MustCompile(`^tgz/[A-Za-z0-9._-]+\.tgz$`) -// distPkg is what the dist branch has of the package, nil when it has -// none, the package isn't one of its scope, or the branch can't be read. -func distPkg(ctx context.Context, name string) *distPackage { +// distPkg is what the dist branch has of the package: nil with no error +// when the branch was read and has none, or the package isn't one of its +// scope; an error wrapping errDistUnread when that isn't known, as the +// branch couldn't be read (a failed read is not "it has none"). The read +// goes on apart from ctx, and ctx ending is waited for no longer: what +// was read last answers, and a package it doesn't have is unknown. +func distPkg(ctx context.Context, name string) (*distPackage, error) { if !strings.HasPrefix(name, distScope) || distBase == "" { - return nil + return nil, nil + } + distMu.Lock() + stale := distIdx == nil || time.Since(distAt) > distKeep + if stale && distReading == nil && (distOK || distAt.IsZero() || time.Since(distAt) > distWait) { + distReading = make(chan struct{}) + go readDist(context.WithoutCancel(ctx), distReading) + } + reading := distReading + distMu.Unlock() + var waited error + if reading != nil { + select { + case <-reading: + case <-ctx.Done(): + waited = ctx.Err() + } } distMu.Lock() defer distMu.Unlock() - stale := distIdx == nil || time.Since(distAt) > distKeep - if stale && (distOK || distAt.IsZero() || time.Since(distAt) > distWait) { - if idx, err := readDistIndex(ctx); err == nil { - distIdx, distOK = idx, true - } else { - // what was read last stays, until a read works - distOK = false + if distIdx != nil { + if p, ok := distIdx.Packages[name]; ok { + return &p, nil } - distAt = time.Now() } - if distIdx == nil { - return nil + switch { + case waited != nil: + return nil, fmt.Errorf("%w: %w", errDistUnread, waited) + case !distOK && distErr != nil: + return nil, fmt.Errorf("%w: %w", errDistUnread, distErr) + case !distOK: + return nil, errDistUnread } - p, ok := distIdx.Packages[name] - if !ok { - return nil + return nil, nil +} + +// readDist reads the index into distIdx, closing done when it has: the +// last read kept until one works. ctx gives it values only, not its time. +func readDist(ctx context.Context, done chan struct{}) { + c, cancel := context.WithTimeout(ctx, distReadFor) + idx, err := readDistIndex(c) + cancel() + distMu.Lock() + if err == nil { + distIdx, distOK, distErr = idx, true, nil + } else { + // what was read last stays, until a read works + distOK, distErr = false, err } - return &p + distAt = time.Now() + distReading = nil + distMu.Unlock() + close(done) } var ( @@ -208,23 +257,24 @@ func mergeDist(a, b *distIndex) *distIndex { } // distInfo is the package's newest version on the dist branch, as npm's -// /latest would say it, and whether there is one. -func distInfo(ctx context.Context, name string) (NPM, bool) { - d := distPkg(ctx, name) +// /latest would say it, and whether there is one; an error (distPkg's) +// when that isn't known. +func distInfo(ctx context.Context, name string) (NPM, bool, error) { + d, err := distPkg(ctx, name) if d == nil { - return NPM{}, false + return NPM{}, false, err } v, ok := d.Versions[d.Latest] if !ok { - return NPM{}, false + return NPM{}, false, nil } var l npmLatest if json.Unmarshal(v.Manifest, &l) != nil { - return NPM{}, false + return NPM{}, false, nil } info := npmOf(l) info.Version = d.Latest - return info, true + return info, true, nil } // distWanted is the package and version an npm spec asks for, when the @@ -255,9 +305,12 @@ var exactVersion = regexp.MustCompile(`^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0 // plugins/dist (bun.lock names it there, and a later bun add installs it // again from it), and added with bun. installMu held. func installDist(ctx context.Context, bun, name, version string) error { - d := distPkg(ctx, name) + d, err := distPkg(ctx, name) + if err != nil { + return err + } if d == nil { - return fmt.Errorf("the community repo's dist branch has no %s, or can't be read", name) + return fmt.Errorf("the community repo's dist branch has no %s", name) } if version == "latest" { version = d.Latest diff --git a/internal/plugin/dist_test.go b/internal/plugin/dist_test.go index 326dd3ea1..24d9edd45 100644 --- a/internal/plugin/dist_test.go +++ b/internal/plugin/dist_test.go @@ -29,8 +29,9 @@ func fakeDist(t *testing.T, pkgs map[string][]string, tamper bool) { t.Helper() u := distServer(t, pkgs, tamper) forgetDist := func() { + distSettled(t) distMu.Lock() - distIdx, distAt, distOK = nil, time.Time{}, false + distIdx, distAt, distOK, distErr = nil, time.Time{}, false, nil distMu.Unlock() } base := distBase @@ -39,6 +40,23 @@ func fakeDist(t *testing.T, pkgs map[string][]string, tamper bool) { t.Cleanup(func() { distBase = base; forgetDist() }) } +// distSettled waits for a read of the dist branch under way to end: one a +// test started ends with it, never writing into the next test's index. +func distSettled(t *testing.T) { + t.Helper() + distMu.Lock() + reading := distReading + distMu.Unlock() + if reading == nil { + return + } + select { + case <-reading: + case <-time.After(distReadFor + 10*time.Second): + t.Fatal("a read of the dist branch didn't end") + } +} + // distServer serves a copy of the dist branch, as fakeDist describes, and // is its address. func distServer(t *testing.T, pkgs map[string][]string, tamper bool) string { diff --git a/internal/plugin/dist_unread_test.go b/internal/plugin/dist_unread_test.go new file mode 100644 index 000000000..dbc2cdc82 --- /dev/null +++ b/internal/plugin/dist_unread_test.go @@ -0,0 +1,122 @@ +package plugin + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" +) + +// gatedDist serves the dist branch with pkg's versions, its index.json +// answered as fail says: 503 while it is true, and only once open is +// closed. Its address is distBase for the test. +func gatedDist(t *testing.T, pkg string, versions []string, fail *atomic.Bool) (open func()) { + t.Helper() + fakeDist(t, nil, false) + inner := distServer(t, map[string][]string{pkg: versions}, false) + gate := make(chan struct{}) + var once sync.Once + open = func() { once.Do(func() { close(gate) }) } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/index.json" { + select { + case <-gate: + case <-r.Context().Done(): + return + } + if fail != nil && fail.Load() { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + } + res, err := http.Get(inner + r.URL.Path) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer res.Body.Close() + w.WriteHeader(res.StatusCode) + io.Copy(w, res.Body) + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { open(); distSettled(t) }) + was := distMirror + distBase = srv.URL + distMirror = func(string) string { return "" } + t.Cleanup(func() { distMirror = was }) + return open +} + +// A package only the dist branch has (the Chat page, @magpie-community/ +// page-chat, never on npm) whose index.json comes slower than one +// package's ask (npmEach) isn't "not on npm" for the next hour: it is +// unknown, kept as nothing, and once the read that went on ends, the +// next ask has it (ferock on Discord, v0.1.2399: Coming soon). +func TestDistReadSlowerThanAnAskIsntMissing(t *testing.T) { + sandbox(t) + const pkg = "@magpie-community/page-chat" + npmHasNothing(t) + open := gatedDist(t, pkg, []string{"0.1.6", "0.1.7"}, nil) + npmEach, npmAll = 200*time.Millisecond, time.Second + + if info, ok := Info(context.Background(), []string{pkg})[pkg]; ok { + t.Fatalf("with the dist branch not read yet the market says %+v; want it unknown", info) + } + npmMu.Lock() + e, kept := npmCached()[pkg] + npmMu.Unlock() + if kept { + t.Fatalf("kept %+v as what npm said, with the dist branch unread", e) + } + c, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + _, err := npmAsk(c, pkg) + cancel() + if errors.Is(err, errNotFound) || !errors.Is(err, errDistUnread) { + t.Fatalf("npmAsk with the dist branch unread: %v; want errDistUnread, not errNotFound", err) + } + + // the read wasn't cut off with the ask: it ends once the branch + // answers, and the next ask has its 0.1.7 + open() + distSettled(t) + if info := Info(context.Background(), []string{pkg})[pkg]; info.Version != "0.1.7" { + t.Fatalf("once the dist branch answered the market says %+v; want its 0.1.7", info) + } +} + +// A dist branch that answers with an error is unknown too, never "not on +// npm", and is asked again once distWait has passed. +func TestDistReadFailedIsntMissing(t *testing.T) { + sandbox(t) + const pkg = "@magpie-community/page-chat" + npmHasNothing(t) + var fail atomic.Bool + fail.Store(true) + open := gatedDist(t, pkg, []string{"0.1.7"}, &fail) + open() + wait := distWait + distWait = 0 + t.Cleanup(func() { distWait = wait }) + npmEach, npmAll = 5*time.Second, 10*time.Second + + if info, ok := Info(context.Background(), []string{pkg})[pkg]; ok { + t.Fatalf("with the dist branch failing the market says %+v; want it unknown", info) + } + if _, err := npmAsk(context.Background(), pkg); errors.Is(err, errNotFound) { + t.Fatalf("npmAsk with the dist branch failing: %v, said missing", err) + } + fail.Store(false) + if info := Info(context.Background(), []string{pkg})[pkg]; info.Version != "0.1.7" { + t.Fatalf("once the dist branch answered the market says %+v; want its 0.1.7", info) + } + // and a branch read that has no such package is missing, as before + const gone = "@magpie-community/opencode-nothing-auth" + if _, err := npmAsk(context.Background(), gone); !errors.Is(err, errNotFound) { + t.Fatalf("npmAsk of a package neither has: %v; want errNotFound", err) + } +} diff --git a/internal/plugin/dist_updates_test.go b/internal/plugin/dist_updates_test.go index b7dd9f7f8..05698195f 100644 --- a/internal/plugin/dist_updates_test.go +++ b/internal/plugin/dist_updates_test.go @@ -90,7 +90,7 @@ func TestDistIndexFromTheMirrorAloneWhenGitHubFails(t *testing.T) { t.Cleanup(func() { distMirror = was }) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - if info, ok := distInfo(ctx, pkg); !ok || info.Version != "0.2.4" { + if info, ok, _ := distInfo(ctx, pkg); !ok || info.Version != "0.2.4" { t.Fatalf("distInfo = %+v, %v; want the mirror's 0.2.4", info, ok) } } @@ -111,7 +111,7 @@ func TestDistIndexDoesntWaitOutAHangingGitHub(t *testing.T) { t.Cleanup(func() { distMirror, distGrace = was, grace }) ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - if info, ok := distInfo(ctx, pkg); !ok || info.Version != "0.2.4" { + if info, ok, _ := distInfo(ctx, pkg); !ok || info.Version != "0.2.4" { t.Fatalf("distInfo = %+v, %v; want the mirror's 0.2.4", info, ok) } if ctx.Err() != nil { diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 5b3412e7b..ea7f60928 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -478,9 +478,16 @@ func npmAsk(ctx context.Context, name string) (NPM, error) { // a @magpie-community package npm doesn't have yet, or has an older // version of, is as the community repo's dist branch has it, which // magpie installs it from (dist.go) - if d, ok := distInfo(ctx, name); ok && (latestErr != nil || update.Newer(d.Version, info.Version)) { + d, ok, derr := distInfo(ctx, name) + if ok && (latestErr != nil || update.Newer(d.Version, info.Version)) { info, latestErr = d, nil } + // npm not having it is "missing" only once the dist branch has + // said it hasn't either: the branch not read leaves it unknown, and + // it is asked again, not kept as missing for an hour (ferock) + if errors.Is(latestErr, errNotFound) && derr != nil { + latestErr = derr + } info.Weekly = weekly if latestErr != nil { return NPM{}, latestErr @@ -635,9 +642,13 @@ func Readme(ctx context.Context, name string) (Page, error) { if err != nil { // one npm doesn't have (yet): the README the community repo's // dist branch packed with it - if d := distPkg(ctx, name); d != nil && d.Readme != "" { + d, derr := distPkg(ctx, name) + if d != nil && d.Readme != "" { return Page{Readme: d.Readme}, nil } + if errors.Is(err, errNotFound) && derr != nil { + return Page{}, derr // not known to be missing + } return Page{}, err } var d struct {