till's Plugins page said "无法连接 GitHub: GitHub refused GITHUB_TOKEN (no GitHub token is set in Settings → Network and sharing)". ghtoken.Token falls back to the environment's GITHUB_TOKEN / GH_TOKEN, and a stale one there made every GitHub read fail, though GitHub serves the same reads without a token. ghtoken.Do now sends a GitHub API request with the token. When the token came from the environment and GitHub answers 401, it remembers that token as refused for the rest of the process (Token() skips it, so GH_TOKEN is still tried after a refused GITHUB_TOKEN, and Settings no longer shows it) and asks once more without Authorization, returning that answer. A token set in Settings is never dropped: its 401 is still Refused()'s error. An anonymous rate limit after the drop is said by LimitedBy as before. Every caller goes through it: plugin fetchJSONFrom (tagged-repo search, git plugin checks, githubHead) and getURLFrom (Bun), and library apiGet, skills fetch, skilltree fetchBlob and latestRTK via doGitHub. internal/davsync/github.go stays strict: its token is the one the user gave sync to write a private repo, outside ghtoken, and an anonymous retry can't write there, so it would only hide why sync failed. Tests (httptest only): ghtoken_test covers an env token refused then asked again without, not sent again (and GH_TOKEN tried next), a Settings token refused stays an error, an env token refused then an anonymous rate limit is reported, and another host untouched. plugin TestTaggedReposStaleEnvTokenDropped is till's case: TaggedRepos with GITHUB_TOKEN=stale-till lists 7 repos, no error. github_token_test and library TestGitHubRateLimitSaid now expect the env token dropped and the Settings token still refused. Broken by hand, each red: (a) no anonymous retry: every new env test, the plugin and library tests red, and TestTaggedReposStaleEnvTokenDropped shows till's exact error; (b) no memory of the refusal: NotSentAgain, the plugin and library tests red; (c) a Settings token also retried: SettingsTokenRefusedStaysAnError, the plugin and library tests red. Run on the commit before the rebase (base9b04c4e20): - gofmt -l: clean. go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows: clean. - set -o pipefail; go test -timeout 45m ./... at load ~30: 62 packages ok. agent, gateway and library ran past 45m while still progressing; gui failed TestSetAnswersWhileDevinAndProvidersHang (set took 10.26s, #1375) and TestMainWindowCorners (measuring killed, #1936/#2645); provider failed TestPluginPicksComeBackWithTheirList (#3051, fixed on main inc922225f1). - Each rerun alone at load 21-56: library ok 809.7s, provider ok 308.8s, gui ok 159.5s, agent ok 1673.3s, gateway ok 780.4s. After rebasing ontoa3ebed202(main moved 8 commits): gofmt -l clean; go vet darwin, linux -tags nogui, windows clean; go test -count=1 at load ~57: ghtoken ok 2.9s, plugin ok 277.6s, library ok 144.2s.
339 lines
11 KiB
Go
339 lines
11 KiB
Go
package plugin
|
|
|
|
import (
|
|
"archive/zip"
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"runtime"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/ghtoken"
|
|
"github.com/yetone/magpie/internal/libc"
|
|
"github.com/yetone/magpie/internal/netproxy"
|
|
"github.com/yetone/magpie/internal/source"
|
|
)
|
|
|
|
// BunVersion is the Bun magpie downloads to run plugins with the first
|
|
// time one is needed, and the oldest it runs them on: newer releases are
|
|
// taken as they come (see CheckBun). Update bunSums below, testenv.MinBun
|
|
// and test.yml's bun-version when it changes.
|
|
const BunVersion = "1.4.2"
|
|
|
|
// bunSums are the SHA-256s of BunVersion's builds, from Bun's own
|
|
// SHASUMS256.txt. They let the default Bun be downloaded through a mirror
|
|
// when Bun's GitHub release page can't be reached.
|
|
var bunSums = map[string]string{
|
|
"bun-darwin-aarch64.zip": "90987a3a16d7db556d886ac3d551e7b6d3edf0a1cf43acaed622e8676be1d12f",
|
|
"bun-darwin-x64.zip": "80520d7e17526308c9185d261679ac6d27798d3803a0e9f7ff9121ab8affb012",
|
|
"bun-linux-aarch64.zip": "54328bbc2d9c8e0c9f892c544d66c57a83b84139e34909e5ee81758f1ac8fda7",
|
|
"bun-linux-x64-baseline.zip": "c678040f14fe0440eb839d37cbd0ce4c051a32da72806ac97de6a6aab6bf728f",
|
|
"bun-linux-aarch64-musl.zip": "71760b6c8ea30623b81a4907cb815d48e2ea266f2e73e751534a44a0607950df",
|
|
"bun-linux-x64-musl-baseline.zip": "76e1db84e98f22f78de0a87e309bfbbf297732847f9720db36750646c85c8c18",
|
|
"bun-windows-x64-baseline.zip": "78c221c2376f79731ccf4e4af0b3bb46d81fefa3296c5abee09ad8a1b21e68c6",
|
|
"bun-windows-aarch64.zip": "a7a16b876a305fd1029c66dbd27007b4f6112ae896532f675878731a21e50cfd",
|
|
"bun-linux-aarch64-android.zip": "a1c7e2983f1bb65146beb256a4d72449f23042412bc2cf278aa6397ba27e0274",
|
|
"bun-linux-x64-android-baseline.zip": "fe36d8d4795e0eadc22fb6696d44d168491c2e5b9b7cbb12b8c96b0c0c40a4f9",
|
|
}
|
|
|
|
func bunChecksum(version, target string) string {
|
|
if version != BunVersion {
|
|
return ""
|
|
}
|
|
return bunSums[target+".zip"]
|
|
}
|
|
|
|
// bunRelease is where Bun's releases are; a var for tests.
|
|
var bunRelease = "https://github.com/oven-sh/bun/releases/download"
|
|
|
|
var bunMu sync.Mutex
|
|
|
|
// bunPlatform is this machine as Bun's builds tell them apart: its OS, its
|
|
// architecture, and whether it is a Linux on musl (Alpine), where Bun's
|
|
// glibc builds can't start (#1877). A var for tests.
|
|
var bunPlatform = func() (goos, goarch string, musl bool) {
|
|
return runtime.GOOS, runtime.GOARCH, libc.Musl()
|
|
}
|
|
|
|
// bunTarget is the name of Bun's build for this machine: bun-darwin-aarch64
|
|
// and the like. x64 Linux and Windows get the baseline build, which runs
|
|
// on CPUs without AVX2 as well; arm64 has no baseline build, on Windows
|
|
// either; a musl Linux gets the musl build.
|
|
func bunTarget() (string, error) {
|
|
return bunTargetFor(bunPlatform())
|
|
}
|
|
|
|
func bunTargetFor(goos, goarch string, musl bool) (string, error) {
|
|
arch := map[string]string{"arm64": "aarch64", "amd64": "x64"}[goarch]
|
|
if arch == "" {
|
|
return "", fmt.Errorf("Bun has no build for %s/%s", goos, goarch)
|
|
}
|
|
switch goos {
|
|
case "darwin":
|
|
case "linux":
|
|
if musl {
|
|
// arm64 has no baseline build, musl or not
|
|
t := "bun-linux-" + arch + "-musl"
|
|
if arch == "x64" {
|
|
t += "-baseline"
|
|
}
|
|
return t, nil
|
|
}
|
|
case "android":
|
|
t := "bun-linux-" + arch + "-android"
|
|
if arch == "x64" {
|
|
t += "-baseline"
|
|
}
|
|
return t, nil
|
|
case "windows":
|
|
// Windows on ARM has Bun's native bun-windows-aarch64 (#2183)
|
|
default:
|
|
return "", fmt.Errorf("Bun has no build for %s", goos)
|
|
}
|
|
t := "bun-" + goos + "-" + arch
|
|
if arch == "x64" && goos != "darwin" {
|
|
t += "-baseline"
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
func bunExe() string {
|
|
if runtime.GOOS == "windows" {
|
|
return "bun.exe"
|
|
}
|
|
return "bun"
|
|
}
|
|
|
|
// missingLibRe finds what a musl Linux's loader says when a program needs
|
|
// a library the system lacks: "Error loading shared library
|
|
// libstdc++.so.6: No such file or directory (needed by …)".
|
|
var missingLibRe = regexp.MustCompile(`Error loading shared library ([^:\s]+)`)
|
|
|
|
// missingLibs says which libraries a bun that started couldn't be linked
|
|
// with lacks, from what it printed, "" when that isn't why it failed. Bun's
|
|
// musl build needs libstdc++ and libgcc, which a bare Alpine doesn't have
|
|
// (#1877); the loader's first line names them, under a screenful of
|
|
// "Error relocating" lines.
|
|
func missingLibs(out string) string {
|
|
var libs []string
|
|
for _, m := range missingLibRe.FindAllStringSubmatch(out, -1) {
|
|
if !slices.Contains(libs, m[1]) {
|
|
libs = append(libs, m[1])
|
|
}
|
|
}
|
|
if len(libs) == 0 {
|
|
return ""
|
|
}
|
|
return fmt.Sprintf("this system lacks %s, which Bun needs (on Alpine: apk add libstdc++ libgcc), or set MAGPIE_BUN to a bun that runs here", strings.Join(libs, ", "))
|
|
}
|
|
|
|
// whyDied adds to the error of a host that died starting what the bun it
|
|
// ran on says when asked its version, when that is a library it lacks.
|
|
func whyDied(ctx context.Context, bun string, err error) error {
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
out, verr := command(ctx, bun, "--version").CombinedOutput()
|
|
if verr == nil {
|
|
return err
|
|
}
|
|
if hint := missingLibs(string(out)); hint != "" {
|
|
return fmt.Errorf("%s: %w", hint, err)
|
|
}
|
|
return err
|
|
}
|
|
|
|
// cantStart says what it means when a bun that is on disk can't be
|
|
// started with "no such file or directory": not that the file is missing,
|
|
// but that the interpreter it names is. A glibc build on a musl Linux
|
|
// (Alpine) names glibc's loader, which isn't there (#1877). Any other
|
|
// error is given back as it is.
|
|
func cantStart(bun string, err error) error {
|
|
if err == nil || !errors.Is(err, fs.ErrNotExist) {
|
|
return err
|
|
}
|
|
if fi, serr := os.Stat(bun); serr != nil || fi.IsDir() {
|
|
return err
|
|
}
|
|
if b := os.Getenv("MAGPIE_BUN"); b != "" && b == bun {
|
|
return fmt.Errorf("this system can't start $MAGPIE_BUN (%s), though it is there: it is likely a build for another C library than this system's (glibc or musl), whose loader isn't here: %w", bun, err)
|
|
}
|
|
target, _ := bunTarget()
|
|
return fmt.Errorf("this system can't start the Bun magpie downloaded (%s, %s), though it is there: the build doesn't match this system's C library (glibc or musl). Set MAGPIE_BUN to a bun built for this system to run plugins on it: %w", target, bun, err)
|
|
}
|
|
|
|
// 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.
|
|
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) {
|
|
return exe, nil
|
|
}
|
|
if err := downloadBun(ctx, v, exe); err != nil {
|
|
return "", fmt.Errorf("downloading Bun %s to run plugins: %w", v, err)
|
|
}
|
|
return exe, nil
|
|
}
|
|
|
|
// HasBun is whether a Bun is at hand without a download.
|
|
func HasBun() bool {
|
|
if os.Getenv("MAGPIE_BUN") != "" {
|
|
return true
|
|
}
|
|
bunMu.Lock()
|
|
defer bunMu.Unlock()
|
|
return haveBun(inUseLocked())
|
|
}
|
|
|
|
func downloadBun(ctx context.Context, version, exe string) error {
|
|
target, err := bunTarget()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
base := bunRelease + "/bun-v" + version + "/"
|
|
want := bunChecksum(version, target)
|
|
if want == "" {
|
|
sums, err := getURLOfficial(ctx, base+"SHASUMS256.txt", 1<<20)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sc := bufio.NewScanner(strings.NewReader(string(sums)))
|
|
for sc.Scan() {
|
|
f := strings.Fields(sc.Text())
|
|
if len(f) == 2 && f[1] == target+".zip" {
|
|
want = f[0]
|
|
}
|
|
}
|
|
if want == "" {
|
|
return fmt.Errorf("%s.zip isn't in the release's checksums", target)
|
|
}
|
|
}
|
|
z, err := getURL(ctx, base+target+".zip", 200<<20)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
sum := sha256.Sum256(z)
|
|
if hex.EncodeToString(sum[:]) != want {
|
|
return errors.New("the download's checksum doesn't match the release's")
|
|
}
|
|
zr, err := zip.NewReader(bytes.NewReader(z), int64(len(z)))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, f := range zr.File {
|
|
if filepath.Base(f.Name) != bunExe() || f.FileInfo().IsDir() {
|
|
continue
|
|
}
|
|
rc, err := f.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rc.Close()
|
|
if err := os.MkdirAll(filepath.Dir(exe), 0o755); err != nil {
|
|
return err
|
|
}
|
|
tmp := exe + ".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, rc); err != nil {
|
|
out.Close()
|
|
os.Remove(tmp)
|
|
return err
|
|
}
|
|
if err := out.Close(); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, exe)
|
|
}
|
|
return fmt.Errorf("%s.zip has no %s", target, bunExe())
|
|
}
|
|
|
|
func getURL(ctx context.Context, url string, limit int64) ([]byte, error) {
|
|
return getURLFrom(ctx, url, limit, true)
|
|
}
|
|
|
|
func getURLOfficial(ctx context.Context, url string, limit int64) ([]byte, error) {
|
|
return getURLFrom(ctx, url, limit, false)
|
|
}
|
|
|
|
func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Bun's newest release is asked of GitHub's API: with the user's
|
|
// GitHub token, as every request magpie makes to it is (#1942)
|
|
res, _, err := ghtoken.Do(req, githubAPI, func(r *http.Request) (*http.Response, error) {
|
|
if mirror {
|
|
return source.Do(http.DefaultClient, r)
|
|
}
|
|
return source.DoOfficial(http.DefaultClient, r)
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("%s: %s", url, res.Status)
|
|
}
|
|
b, err := io.ReadAll(io.LimitReader(res.Body, limit+1))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if int64(len(b)) > limit {
|
|
return nil, fmt.Errorf("%s: too large", url)
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
// bunCommand runs bun with args in dir, the environment's proxy settings
|
|
// passed on (a SOCKS5 one bridged, as Bun can't use it: #1409), the roots
|
|
// the system trusts added to Bun's (caEnv), and npm's registry in China
|
|
// with the 「国内镜像」 switch on (its packages are npm's own, checked
|
|
// against the integrity npm gave).
|
|
var bunCommand = func(ctx context.Context, bun, dir string, args ...string) *exec.Cmd {
|
|
cmd := command(ctx, bun, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(netproxy.EnvForBun(env()), "BUN_INSTALL_CACHE_DIR="+installCacheDir())
|
|
cmd.Env = append(cmd.Env, caEnv(cmd.Env, dir)...)
|
|
cmd.Env = append(cmd.Env, registryEnv(cmd.Env)...)
|
|
return cmd
|
|
}
|
|
|
|
// registryEnv is what has bun install from npm's registry in China, with
|
|
// the switch on, unless the environment names a registry already.
|
|
func registryEnv(env []string) []string {
|
|
if !source.China() {
|
|
return nil
|
|
}
|
|
for _, kv := range env {
|
|
k, v, _ := strings.Cut(kv, "=")
|
|
if k = strings.ToUpper(k); (k == "BUN_CONFIG_REGISTRY" || k == "NPM_CONFIG_REGISTRY") && strings.TrimSpace(v) != "" {
|
|
return nil
|
|
}
|
|
}
|
|
return []string{"BUN_CONFIG_REGISTRY=" + source.NPMMirror + "/"}
|
|
}
|