Files
magpie/internal/plugin/github.go
T
yetone 48e59c5b89 plugin: the unofficial plugins on GitHub aren't cut short through a slow proxy, and a list cut short is asked again in 20s, not kept ten minutes (larchsis on X)
larchsis (Windows, no system proxy, magpie's own proxy on) saw no
unofficial plugins on the Plugins page, and saw them with the system
proxy on and magpie's set to automatic.

No request bypasses magpie's proxy. Every listing and install read
(market.json, npm info and search, GitHub's search, package.json and
README, Bun's download, plugin icons) goes through http.DefaultClient or
DefaultTransport, which netproxy.Install routes through settings.Proxy,
else the environment, else the system proxy (HKCU Internet Settings on
Windows). Checked with a counting CONNECT proxy in a sandbox magpie on
macOS and on the Windows box: every connection to api.github.com,
raw.githubusercontent.com and registry.npmjs.org went through it, and
lsof / Get-NetTCPConnection showed none going direct.

The cause is timing. askTagged gave the whole listing 8s, six package.json
reads at once, each bounded by that same 8s, and a repository whose read
hadn't finished was left out. The cut list was then kept ten minutes, and
on disk for a restart. Through a sandbox proxy that adds latency per
chunk: no delay 29 repos, 150ms 21, 300ms 6. A slow proxy loses most of
"Unofficial, on GitHub", and when it loses all of them the section is gone.
The two setups differ in latency and in what was cached, not in proxy
handling.

Now:
- Reads go on past the page's wait (taggedEach 20s each, 12 at once), on a
  context detached from the request. They are kept by repository and push,
  as before, so the next ask has them.
- A repository whose read didn't come in time is as the last list had it
  (in memory, else on disk), with the search's current stars and
  description.
- A list that left one out is asked again after 20s, not ten minutes. Its
  copy on disk is dated so that a restarted magpie asks again too.

Run:
- TestTaggedReposSlowRead (new) holds word-guard's package.json past a
  300ms wait. It fails on the old code (5 repos, word-guard missing). It
  also fails with each part broken by hand: no fallback to the last list,
  a partial list kept 10 minutes, reads cancelled at the wait, and the disk
  copy not aged back.
- Sandbox magpie web (own HOME, own ports, proxy 127.0.0.1:3481 with
  injected latency), no cache: at 300ms 11 repos at 8s, then all 29 25s
  later (the old code kept 6 for ten minutes). At 1s none at first, all 29
  25s later.
- go test ./... on 5e7efce3b (origin/main): green. go test -race -count=5
  on the tagged tests. gofmt -l clean. go vet on darwin, GOOS=windows
  ./..., GOOS=linux -tags nogui ./internal/plugin.
- Windows box: plugin.test.exe with the tagged tests, 3 of 3. In the full
  package run only TestMarketIconsAreBundled failed, because it reads
  ../gui/assets, which wasn't copied over.
2026-10-12 17:45:54 +08:00

434 lines
14 KiB
Go

package plugin
import (
"context"
"encoding/json"
"errors"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
)
// Plugins on GitHub that nobody listed: a repository its author tagged
// with the magpie-plugin topic. The market shows them apart from the
// community's, as not reviewed by anyone: installed from npm when its
// author published it there from the repository, else from the repository
// itself (github:owner/repo).
// Topic is the GitHub topic that puts a repository on the Plugins page.
const Topic = "magpie-plugin"
// Tagged is a repository tagged with Topic.
type Tagged struct {
Spec string `json:"spec"` // what Install adds: its npm name when npm has it from this repository, else github:owner/repo
Repo string `json:"repo"` // owner/repo
URL string `json:"url"` // its page on GitHub
Owner string `json:"owner"` // its owner's login
OwnerAvatar string `json:"ownerAvatar,omitempty"`
Description string `json:"description,omitempty"`
Stars int `json:"stars"`
License string `json:"license,omitempty"` // SPDX id
Pushed time.Time `json:"pushed"`
// from its package.json on the default branch: what bun will install
// it as, its version, and whether it is gateway middleware or an agent
Package string `json:"package,omitempty"`
Version string `json:"version,omitempty"`
Kind string `json:"kind,omitempty"` // "middleware" or "agent" when that is all it is
// its package.json's magpie.icon, as an installed plugin gives its
// provider one: an https URL or a data:image URI, as it is written
Icon string `json:"icon,omitempty"`
}
// Where GitHub is asked, moved by tests.
var (
githubAPI = "https://api.github.com"
githubRaw = "https://raw.githubusercontent.com"
)
// taggedTTL is how long what GitHub said stands: short, so a repository
// tagged a moment ago shows within minutes (lee04052822 on X tagged theirs
// and, asked six hours apart, didn't see it). A search is one request of
// the ten a minute; what each repository's package.json and npm said is
// kept while its last push stays the same, so asking again costs no more.
const taggedTTL = 10 * time.Minute
// taggedWait is how long the page waits for GitHub; taggedEach bounds a
// repository's reads (package.json, npm, its entry file), which go on past
// that wait and are kept for the next ask; taggedAtOnce repositories are
// read at once; and a list that left a repository out for want of an
// answer is asked again after taggedRetry. Through a proxy far away each
// read takes a few hundred milliseconds (larchsis on X: a list cut short
// at the wait was kept ten minutes).
var (
taggedWait = 8 * time.Second
taggedEach = 20 * time.Second
taggedAtOnce = 12
taggedRetry = 20 * time.Second
)
var (
taggedMu sync.Mutex
taggedL []Tagged
taggedAt time.Time
// owner/repo@pushed → what its package.json and npm made of it, nil
// when it was left out
readMu sync.Mutex
readRepo = map[string]*Tagged{}
)
func taggedCache() string { return filepath.Join(filepath.Dir(marketCache()), "plugin-github.json") }
// taggedOnDisk is the list as GitHub said it last, kept on disk; nil
// when there is none.
func taggedOnDisk() []Tagged {
var l []Tagged
if b, err := os.ReadFile(taggedCache()); err == nil {
_ = json.Unmarshal(b, &l)
}
return l
}
// TaggedRepos are the repositories tagged with Topic, the most starred
// first: GitHub asked at most every ten minutes (its search lets 10 a minute
// through without a token), else what it said last, kept on disk. Archived
// repositories, forks and magpie-community's own (the market lists those)
// are left out, as is one whose package.json doesn't parse, which bun
// couldn't install either. A repository whose package.json didn't come in
// time is as the list had it last, and the list is asked again in
// taggedRetry. MAGPIE_PLUGIN_MARKET=off keeps to none.
func TaggedRepos(ctx context.Context) []Tagged {
taggedMu.Lock()
defer taggedMu.Unlock()
if taggedL != nil && time.Since(taggedAt) < taggedTTL {
return taggedL
}
if os.Getenv("MAGPIE_PLUGIN_MARKET") == "off" {
return []Tagged{}
}
// a magpie started again within the ten minutes: what GitHub said then,
// without the wait of asking (a package.json read for each)
if taggedL == nil {
if fi, err := os.Stat(taggedCache()); err == nil && time.Since(fi.ModTime()) < taggedTTL {
if l := taggedOnDisk(); l != nil {
taggedL, taggedAt = l, fi.ModTime()
return l
}
}
}
last := taggedL
if last == nil {
last = taggedOnDisk()
}
if l, whole, err := askTagged(ctx, last); err == nil {
taggedL, taggedAt = l, time.Now()
if !whole {
taggedAt = time.Now().Add(-taggedTTL + taggedRetry)
}
if b, err := json.Marshal(l); err == nil {
_ = os.MkdirAll(filepath.Dir(taggedCache()), 0o755)
_ = os.WriteFile(taggedCache(), b, 0o644)
// a magpie started again meanwhile asks again too
_ = os.Chtimes(taggedCache(), taggedAt, taggedAt)
}
return l
}
// GitHub didn't answer: what it said last, asked again in a minute
l := last
if l == nil {
l = []Tagged{}
}
taggedL, taggedAt = l, time.Now().Add(-taggedTTL+time.Minute)
return l
}
// askTagged asks GitHub's search, and reads each repository it names
// that wasn't read at its last push. whole is false when a repository was
// left out for want of an answer in taggedWait: it is then as last had
// it, if it had it.
func askTagged(ctx context.Context, last []Tagged) (l []Tagged, whole bool, err error) {
c, cancel := context.WithTimeout(ctx, taggedWait)
defer cancel()
v := url.Values{"q": {"topic:" + Topic + " archived:false fork:false"}, "sort": {"stars"}, "order": {"desc"}, "per_page": {"50"}}
b, err := fetchJSON(c, githubAPI+"/search/repositories?"+v.Encode(), 4<<20)
if err != nil {
return nil, false, err
}
var r struct {
Items []struct {
FullName string `json:"full_name"`
HTMLURL string `json:"html_url"`
Description string `json:"description"`
Stars int `json:"stargazers_count"`
DefaultBranch string `json:"default_branch"`
Pushed time.Time `json:"pushed_at"`
Archived bool `json:"archived"`
Fork bool `json:"fork"`
Owner struct {
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
} `json:"owner"`
License *struct {
SPDX string `json:"spdx_id"`
} `json:"license"`
} `json:"items"`
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, false, err
}
before := map[string]Tagged{}
for _, t := range last {
before[strings.ToLower(t.Repo)] = t
}
// what the search says now, over what is kept of a repository
fresh := func(r, t Tagged) Tagged {
r.URL, r.Owner, r.OwnerAvatar, r.Description, r.Stars, r.License, r.Pushed = t.URL, t.Owner, t.OwnerAvatar, t.Description, t.Stars, t.License, t.Pushed
return r
}
var mu sync.Mutex // out, keep, done; late once the page stops waiting
late := false
out := make([]Tagged, len(r.Items))
keep := make([]bool, len(r.Items))
done := make([]bool, len(r.Items))
asked := make([]Tagged, len(r.Items))
var wg sync.WaitGroup
sem := make(chan struct{}, taggedAtOnce)
// a read goes on after the page stops waiting, and is kept for the
// next ask
bg := context.WithoutCancel(ctx)
seen := map[string]bool{}
for i, it := range r.Items {
if it.Archived || it.Fork || strings.EqualFold(it.Owner.Login, "magpie-community") || !strings.Contains(it.FullName, "/") {
done[i] = true
continue
}
t := Tagged{
Spec: "github:" + it.FullName, Repo: it.FullName, URL: it.HTMLURL, Owner: it.Owner.Login, OwnerAvatar: it.Owner.AvatarURL,
Description: it.Description, Stars: it.Stars, Pushed: it.Pushed,
}
if it.License != nil && it.License.SPDX != "NOASSERTION" {
t.License = it.License.SPDX
}
asked[i] = t
key := it.FullName + "@" + it.Pushed.Format(time.RFC3339)
seen[key] = true
readMu.Lock()
was, read := readRepo[key]
readMu.Unlock()
if read {
if was != nil {
out[i], keep[i] = fresh(*was, t), true
}
done[i] = true
continue
}
wg.Add(1)
go func(i int, t Tagged, branch string) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
pc, cancel := context.WithTimeout(bg, taggedEach)
defer cancel()
got, ok, read := readTagged(pc, t, branch)
if read {
readMu.Lock()
if ok {
readRepo[key] = &got
} else {
readRepo[key] = nil
}
readMu.Unlock()
}
mu.Lock()
if !late {
out[i], keep[i] = got, ok
// a package.json GitHub didn't answer for: not known
done[i] = ok || read
}
mu.Unlock()
}(i, t, it.DefaultBranch)
}
waited := make(chan struct{})
go func() { wg.Wait(); close(waited) }()
select {
case <-waited:
case <-c.Done():
}
mu.Lock()
late = true
mu.Unlock()
// a repository pushed to again, or no longer tagged, is forgotten
readMu.Lock()
for k := range readRepo {
if !seen[k] {
delete(readRepo, k)
}
}
readMu.Unlock()
l, whole = []Tagged{}, true
for i := range out {
switch {
case keep[i]:
l = append(l, out[i])
case !done[i]:
whole = false
if was, ok := before[strings.ToLower(asked[i].Repo)]; ok {
l = append(l, fresh(was, asked[i]))
}
}
}
return l, whole, nil
}
// readTagged reads a tagged repository's package.json (on branch), and
// npm's copy of the package it names: t as it is installed, whether it is
// kept, and whether that is known (GitHub or npm not answering is not,
// and it is read again next time).
func readTagged(pc context.Context, t Tagged, branch string) (Tagged, bool, bool) {
if branch == "" {
branch = "HEAD"
}
pb, err := fetchJSON(pc, githubRaw+"/"+t.Repo+"/"+url.PathEscape(branch)+"/package.json", 2<<20)
if err != nil {
return t, false, errors.Is(err, errNotFound)
}
var pj struct {
Name string `json:"name"`
Version string `json:"version"`
Main string `json:"main"`
Exports json.RawMessage `json:"exports"`
Magpie struct {
Middleware string `json:"middleware"`
Agent string `json:"agent"`
Icon string `json:"icon"`
} `json:"magpie"`
}
if json.Unmarshal(pb, &pj) != nil || !pkgName.MatchString(pj.Name) {
return t, false, true
}
t.Package, t.Version = pj.Name, pj.Version
// a picture, as host.js's iconOf takes one: magpie checks and
// keeps it before the page shows it (the GUI's /api/plugins/github)
t.Icon = ownIcon(pj.Magpie.Icon)
if pj.Main == "" && len(pj.Exports) == 0 {
switch {
case strings.TrimSpace(pj.Magpie.Middleware) != "":
t.Kind = "middleware"
case strings.TrimSpace(pj.Magpie.Agent) != "":
t.Kind = "agent"
}
}
// published to npm from this repository: npm's copy is the one
// built to be installed (a repository often leaves its dist out,
// built only to publish), so it is installed from npm
b, err := fetchJSON(pc, npmRegistry+"/"+npmPath(pj.Name)+"/latest", 1<<20)
known := err == nil || errors.Is(err, errNotFound)
// npmNames is whether npm's copy names what it loads (main,
// exports); one that names nothing loads an index file
npmNames := false
if err == nil {
var l npmLatest
if json.Unmarshal(b, &l) == nil && l.Version != "" && strings.EqualFold(githubRepo(repoURL(l.Repository)), t.Repo) {
t.Spec, t.Version = pj.Name, l.Version
npmNames = l.Main != "" || len(l.Exports) > 0
}
}
// installed from the repository, the file it loads must be in
// it: one whose dist is built only to publish couldn't load
// (GitHub not answering is no answer, and keeps it; so is a
// name Bun would add .js or /index.js to). Installed from npm,
// a copy that names no file loads index.js, which the
// repository has too when it is a plugin at all: a package
// that is only a command (bin), an MCP server, has none and
// would never load (#1327)
if IsGit(t.Spec) || !npmNames {
entry := pj.Magpie.Middleware
if t.Kind == "agent" {
entry = pj.Magpie.Agent
} else if t.Kind != "middleware" {
entry = pkgEntry(pj.Exports, pj.Main)
if !IsGit(t.Spec) {
entry = pkgEntry(nil, "")
}
}
if path.Ext(entry) != "" {
_, err := fetchJSON(pc, githubRaw+"/"+t.Repo+"/"+url.PathEscape(branch)+"/"+strings.TrimPrefix(path.Clean("/"+entry), "/"), 1)
if errors.Is(err, errNotFound) {
return t, false, known
}
known = known && err == nil
}
}
return t, true, known
}
// pkgEntry is the file importing a package loads, as Bun resolves it: its
// exports' "." (import, else default), else main, else index.js.
func pkgEntry(exports json.RawMessage, main string) string {
var pick func(v any) string
pick = func(v any) string {
switch v := v.(type) {
case string:
return v
case map[string]any:
if d, ok := v["."]; ok {
return pick(d)
}
for _, k := range []string{"bun", "import", "default", "node", "require"} {
if s := pick(v[k]); s != "" {
return s
}
}
}
return ""
}
var v any
if len(exports) > 0 && json.Unmarshal(exports, &v) == nil {
if s := pick(v); s != "" {
return s
}
}
if main != "" {
return main
}
return "index.js"
}
// githubReadme is the README of a GitHub repository not installed yet, as
// its default branch has it.
func githubReadme(ctx context.Context, repo string) (Page, error) {
ctx, cancel := context.WithTimeout(ctx, 12*time.Second)
defer cancel()
var last error
for _, f := range []string{"README.md", "readme.md", "Readme.md", "README"} {
b, err := fetchJSON(ctx, githubRaw+"/"+repo+"/HEAD/"+f, 200<<10)
if err == nil {
return Page{Readme: string(b)}, nil
}
last = err
}
return Page{}, last
}
// githubRepo is owner/repo of a github: spec or a GitHub page's URL, ""
// for any other.
func githubRepo(spec string) string {
s := strings.TrimSuffix(strings.SplitN(spec, "#", 2)[0], ".git")
switch {
case strings.HasPrefix(s, "github:"):
s = strings.TrimPrefix(s, "github:")
case strings.HasPrefix(s, "https://github.com/"), strings.HasPrefix(s, "https://www.github.com/"):
s = s[strings.Index(s, "github.com/")+len("github.com/"):]
default:
return ""
}
p := strings.Split(strings.Trim(s, "/"), "/")
if len(p) < 2 || p[0] == "" || p[1] == "" {
return ""
}
return p[0] + "/" + p[1]
}