diff --git a/internal/update/apiroute.go b/internal/update/apiroute.go index b85b2a0fb..fd9286af9 100644 --- a/internal/update/apiroute.go +++ b/internal/update/apiroute.go @@ -20,7 +20,8 @@ import ( // download whose github.com address is busy goes on there (download): the // same bytes, checked against the feed's hash, and on the Mac against the // installed app's team, exactly as before. A mirror the user gave keeps -// precedence: through one, no API route is tried. +// precedence: through one, no API route is tried. A file the feed names +// on the site's R2 goes on to its github.com address (Asset.GitHub) first. // githubWeb and githubAPI are GitHub's addresses; vars for tests. var ( @@ -29,14 +30,18 @@ var ( ) // apiRoute is the API address of a's file: the feed's (Asset.API), else -// the one GitHub's API lists for the release a.URL names. "" with a nil +// the one GitHub's API lists for the release a.GitHub (or a.URL) names. "" with a nil // error when a's file isn't on GitHub (a test's server, a feed pointed // elsewhere). func apiRoute(ctx context.Context, a Asset) (string, error) { if a.API != "" { return a.API, nil } - rest, ok := strings.CutPrefix(a.URL, githubWeb+"/") + src := a.URL + if a.GitHub != "" { + src = a.GitHub + } + rest, ok := strings.CutPrefix(src, githubWeb+"/") if !ok { return "", nil } diff --git a/internal/update/apiroute_test.go b/internal/update/apiroute_test.go index 550d72076..159bfdfb5 100644 --- a/internal/update/apiroute_test.go +++ b/internal/update/apiroute_test.go @@ -22,6 +22,7 @@ type fakeGitHub struct { direct, tags, asset, blob atomic.Int32 body []byte served []byte // what the blob sends; body unless a test changes it + directServes bool // the download address sends the file instead of 504 sum string assetWithoutOctetStreamAsked atomic.Int32 } @@ -36,6 +37,10 @@ func newFakeGitHub(t *testing.T) *fakeGitHub { switch r.URL.Path { case "/yetone/magpie-releases/releases/download/v0.1.9/magpie.zip": g.direct.Add(1) + if g.directServes { + w.Write(g.served) + return + } w.WriteHeader(http.StatusGatewayTimeout) case "/repos/yetone/magpie-releases/releases/tags/v0.1.9": g.tags.Add(1) @@ -141,3 +146,136 @@ func TestMirrorKeepsPrecedenceOverTheAPIRoute(t *testing.T) { t.Fatalf("download address asked %d times, want every try (%d)", n, len(retryWaits)+1) } } + +// site is usemagpie.ai's /files, the release's copy on R2, answering +// status on every try; it counts the asks. +func site(t *testing.T, status int) (*httptest.Server, *atomic.Int32) { + t.Helper() + var n atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n.Add(1) + w.WriteHeader(status) + })) + t.Cleanup(srv.Close) + return srv, &n +} + +// onR2 is the feed's asset when the site holds the file: the site's +// address, github.com's beside it. +func (g *fakeGitHub) onR2(siteURL string) Asset { + a := g.asset0() + a.GitHub, a.URL = a.URL, siteURL+"/files/v0.1.9/magpie.zip" + return a +} + +// The site's copy failing, the download goes on from github.com's own +// address: once, not after every try of the site's. +func TestDownloadGoesToGitHubWhenTheSiteIsBusy(t *testing.T) { + g := newFakeGitHub(t) + g.directServes = true + s, asked := site(t, http.StatusServiceUnavailable) + path := filepath.Join(t.TempDir(), "magpie.zip") + if err := download(context.Background(), g.onR2(s.URL), path); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(path); string(b) != string(g.body) { + t.Fatalf("file has %d bytes, want the release's %d", len(b), len(g.body)) + } + if asked.Load() != 1 || g.direct.Load() != 1 || g.tags.Load() != 0 { + t.Fatalf("site %d, github.com %d, API %d; want 1, 1, 0", asked.Load(), g.direct.Load(), g.tags.Load()) + } +} + +// The site and github.com both busy: GitHub's API route, looked up from +// the github.com address (the site's says nothing of the release). +func TestDownloadGoesOnToTheAPIFromTheSite(t *testing.T) { + g := newFakeGitHub(t) + s, asked := site(t, http.StatusGatewayTimeout) + path := filepath.Join(t.TempDir(), "magpie.zip") + if err := download(context.Background(), g.onR2(s.URL), path); err != nil { + t.Fatal(err) + } + if asked.Load() != 1 || g.direct.Load() != 1 || g.tags.Load() != 1 || g.blob.Load() != 1 { + t.Fatalf("site %d, github.com %d, tags %d, blob %d; want 1 each", asked.Load(), g.direct.Load(), g.tags.Load(), g.blob.Load()) + } +} + +// Every route failing, the error names each, the site's first. +func TestDownloadSaysEachRouteThatFailed(t *testing.T) { + g := newFakeGitHub(t) + g.served = []byte("not magpie") + s, _ := site(t, http.StatusGatewayTimeout) + host := strings.TrimPrefix(s.URL, "http://") + err := download(context.Background(), g.onR2(s.URL), filepath.Join(t.TempDir(), "magpie.zip")) + if err == nil { + t.Fatal("download went through") + } + msg := err.Error() + for _, want := range []string{"from " + host, "through api.github.com", "does not match its checksum"} { + if !strings.Contains(msg, want) { + t.Fatalf("err = %q, want it to say %q", msg, want) + } + } + if strings.Index(msg, host) > strings.Index(msg, "through api.github.com") { + t.Fatalf("err = %q: the site's failure isn't first", msg) + } +} + +// A file on the site is not put behind the user's mirror (it is no +// GitHub file); github.com's address after it is, and the API is never +// asked through a mirror. +func TestMirrorTakesTheGitHubAddressAfterTheSite(t *testing.T) { + g := newFakeGitHub(t) + s, asked := site(t, http.StatusBadGateway) + var mirrored atomic.Int32 + m := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mirrored.Add(1) + w.WriteHeader(http.StatusGatewayTimeout) + })) + t.Cleanup(m.Close) + oldWeb := githubWeb + t.Cleanup(func() { githubWeb = oldWeb }) + a := g.onR2(s.URL) + // the github.com address as the feed gives it, for mirrored to know + a.GitHub = "https://github.com/yetone/magpie-releases/releases/download/v0.1.9/magpie.zip" + ctx := WithMirror(context.Background(), m.URL+"/") + if err := download(ctx, a, filepath.Join(t.TempDir(), "magpie.zip")); err == nil { + t.Fatal("download went through") + } + if asked.Load() != 1 { + t.Fatalf("site asked %d times, want 1", asked.Load()) + } + if n := mirrored.Load(); n != int32(len(retryWaits)) { + t.Fatalf("mirror asked %d times, want the tries after the site's (%d)", n, len(retryWaits)) + } + if g.tags.Load() != 0 || g.asset.Load() != 0 { + t.Fatalf("GitHub's API asked through a mirror: tags %d, asset %d", g.tags.Load(), g.asset.Load()) + } +} + +// A connection to the site that breaks on every try (not a busy answer) +// still leaves it for github.com before the tries run out. +func TestDownloadLeavesABrokenSiteForGitHub(t *testing.T) { + g := newFakeGitHub(t) + g.directServes = true + var asked atomic.Int32 + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + hj, _ := w.(http.Hijacker) + c, _, _ := hj.Hijack() + c.Close() + })) + t.Cleanup(s.Close) + path := filepath.Join(t.TempDir(), "magpie.zip") + if err := download(context.Background(), g.onR2(s.URL), path); err != nil { + t.Fatal(err) + } + if g.direct.Load() != 1 { + t.Fatalf("github.com asked %d times, want 1", g.direct.Load()) + } + // with the API route still left after github.com, the site has all + // but the last two tries + if want := int32(len(retryWaits) - 1); asked.Load() != want { + t.Fatalf("site asked %d times, want %d", asked.Load(), want) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 8bc20b3f1..7272c48d6 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -67,6 +67,10 @@ type Asset struct { // API is GitHub's API address of the file, asked when URL is busy // (apiroute.go); a feed without it has it looked up from URL. API string `json:"api,omitempty"` + // GitHub is the file's github.com address when URL is another (the + // site's copy on R2): where a download goes on when URL fails, and + // what a mirror the user gave is put in front of. + GitHub string `json:"github,omitempty"` } // client asks the feed and downloads a release through the proxy the rest @@ -1142,12 +1146,17 @@ func download(ctx context.Context, a Asset, path string) error { if err := clearFile(path); err != nil { return err } - var err, direct error - // on, the tries go through GitHub's API route (apiroute.go): once - // the address itself answered busy, which trying it again didn't get - // past on 2026-11-08, or for the last try after connections that - // broke. Never through a mirror the user gave. - on, tried := a, false + var err error + // the tries go to a's own address, then, once it answered busy + // (which trying it again didn't get past on 2026-11-08) or for the + // last tries after connections that broke, to the routes after it: + // github.com's address of a file the feed names elsewhere (GitHub, + // through the user's mirror when one is set), then GitHub's API + // route (apiroute.go), never through a mirror. + on, viaAPI := a, false + toGitHub := a.GitHub != "" && a.GitHub != a.URL + toAPI := mirrorOf(ctx) == "" + var before []string // each route left, and how it failed for try := 0; try <= len(retryWaits); try++ { if try > 0 { step(ctx, StepRetry) @@ -1159,18 +1168,32 @@ func download(ctx context.Context, a Asset, path string) error { } step(ctx, StepDownload) tctx := ctx - if on.URL != a.URL { + if viaAPI { tctx = withAPIRoute(ctx) } if err = fetch(tctx, on, path); err == nil || ctx.Err() != nil || !Network(err) { break } - if !tried && mirrorOf(ctx) == "" && (busyErr(err) || try == len(retryWaits)-1) { - tried = true - if api, aerr := apiRoute(ctx, a); api != "" { - on.URL, direct = api, err - } else if aerr != nil { - err = fmt.Errorf("%w (GitHub's API route couldn't be found: %v)", err, aerr) + left := 0 + if toGitHub { + left++ + } + if toAPI { + left++ + } + if left > 0 && (busyErr(err) || try >= len(retryWaits)-left) { + if toGitHub { + toGitHub = false + before = append(before, fmt.Sprintf("%v (from %s)", err, hostOf(on.URL))) + on.URL = a.GitHub + } else { + toAPI = false + if api, aerr := apiRoute(ctx, a); api != "" { + before = append(before, err.Error()) + on.URL, viaAPI = api, true + } else if aerr != nil { + err = fmt.Errorf("%w (GitHub's API route couldn't be found: %v)", err, aerr) + } } } // the tries after a connection that broke go over HTTP/1.1: a @@ -1180,8 +1203,12 @@ func download(ctx context.Context, a Asset, path string) error { ctx = netproxy.OverHTTP1(ctx) } if err != nil { - if direct != nil { - err = fmt.Errorf("%w, and through api.github.com: %v", direct, err) + if len(before) > 0 { + last := "from " + hostOf(on.URL) + if viaAPI { + last = "through api.github.com" + } + err = fmt.Errorf("%s, and %s: %w", strings.Join(before, ", "), last, err) } if cerr := clearFile(path); cerr != nil { err = errors.Join(err, cerr) @@ -1210,6 +1237,15 @@ func clearFile(path string) error { return fmt.Errorf("couldn't clear the earlier download %s: %w", filepath.Base(path), err) } +// hostOf is u's host, for an error that says where a try went without +// the address itself. +func hostOf(u string) string { + if p, err := url.Parse(u); err == nil && p.Host != "" { + return p.Host + } + return u +} + // NetError is a download the network broke off: the connection failed or // dropped part way. It names the file and the cause, never the address: // GitHub's redirect is a signed URL, hundreds of characters of signature diff --git a/site/install.test.mjs b/site/install.test.mjs index 630fecd6e..45ba6bce3 100644 --- a/site/install.test.mjs +++ b/site/install.test.mjs @@ -42,7 +42,7 @@ function systemPath(dir) { return sys; } -function install(t, { termux = true, arch = "aarch64", override = false, prefixOnly = false, missing = false, corrupt = false, desktop = false, github = false, api = false, args = [], env: extra = {}, tamper = "", libs = desktop, cli = !desktop, distro = "ID=ubuntu\nID_LIKE=debian\n", sessions = [], login = "", tty = false, uid = 1000, sudo = true, pmFails = false, payload = "test binary\n" } = {}) { +function install(t, { termux = true, arch = "aarch64", override = false, prefixOnly = false, missing = false, corrupt = false, desktop = false, github = false, r2 = false, api = false, args = [], env: extra = {}, tamper = "", libs = desktop, cli = !desktop, distro = "ID=ubuntu\nID_LIKE=debian\n", sessions = [], login = "", tty = false, uid = 1000, sudo = true, pmFails = false, payload = "test binary\n" } = {}) { const dir = mkdtempSync(join(tmpdir(), "magpie-install-")); t.after(() => rmSync(dir, { recursive: true, force: true })); const tools = join(dir, "tools"); @@ -61,6 +61,8 @@ function install(t, { termux = true, arch = "aarch64", override = false, prefixO for (const name of new Set([file, `magpie-cli-linux-${cpu}`, `magpie-linux-${cpu}`])) { if (missing && name === file) continue; assets[name] = { url: github ? `https://github.com/yetone/magpie-releases/releases/download/vtest/${name}` : `https://download.invalid/${name}`, sha256: corrupt ? "0".repeat(64) : createHash("sha256").update(payload).digest("hex") }; + // r2: the site's copy, github.com's address beside it + if (r2) assets[name] = { ...assets[name], url: `https://usemagpie.ai/files/vtest/${name}`, github: `https://github.com/yetone/magpie-releases/releases/download/vtest/${name}` }; if (api) assets[name].api = `https://api.github.com/repos/yetone/magpie-releases/releases/assets/${assetId(name)}`; } const requests = join(dir, "requests"); @@ -122,7 +124,7 @@ fs.appendFileSync(process.env.INSTALL_REQUESTS, url + String.fromCharCode(10)); fs.appendFileSync(process.env.INSTALL_ARGS, JSON.stringify(args) + String.fromCharCode(10)); const tamper = process.env.INSTALL_TAMPER; if (url.endsWith("/api/latest")) process.stdout.write(process.env.INSTALL_FEED); -else if (process.env.INSTALL_DOWN && url.startsWith(process.env.INSTALL_DOWN)) process.exit(22); +else if ((process.env.INSTALL_DOWN || "").split(" ").some((p) => p && url.startsWith(p))) process.exit(22); else if (url.includes("/releases/tags/")) process.stdout.write(process.env.INSTALL_TAGS); else if (url.includes("/releases/assets/") && !args.includes("Accept: application/octet-stream")) fs.writeFileSync(args[args.indexOf("-o") + 1], "{}"); else fs.writeFileSync(args[args.indexOf("-o") + 1], tamper && url.startsWith(tamper) ? "changed by the mirror" : process.env.INSTALL_PAYLOAD); @@ -657,3 +659,52 @@ test("a mirror given keeps precedence: it failing, GitHub's API is not asked", ( assert.match(r.stderr, /could not download https:\/\/gh\.mirror\.example\//); assert.doesNotMatch(r.requests, /api\.github\.com/); }); + +// The feed names the site's copy on R2, github.com's address beside it. +test("the site's copy is downloaded, checked against the site's SHA-256", (t) => { + const r = install(t, { termux: false, r2: true, api: true }); + assert.equal(r.status, 0, r.stderr); + assert.equal(readFileSync(join(r.bin, "magpie"), "utf8"), r.payload); + assert.deepEqual(r.requests.trim().split("\n"), ["https://usemagpie.ai/api/latest", "https://usemagpie.ai/files/vtest/magpie-cli-linux-arm64"]); + const bad = install(t, { termux: false, r2: true, corrupt: true }); + assert.notEqual(bad.status, 0); + assert.match(bad.stderr, /does not match its checksum/); + assert.equal(readFileSync(join(bad.bin, "magpie"), "utf8"), "old installation"); +}); + +test("the site's copy failing, github.com's address, then GitHub's API looked up from it", (t) => { + const site = "https://usemagpie.ai/files/", gh = "https://github.com/yetone/magpie-releases/releases/download/vtest/magpie-cli-linux-arm64"; + const r = install(t, { termux: false, r2: true, env: { INSTALL_DOWN: site } }); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(r.requests.trim().split("\n").slice(1), [site + "vtest/magpie-cli-linux-arm64", gh]); + assert.match(r.stdout, /from github\.com instead/); + const both = install(t, { termux: false, r2: true, env: { INSTALL_DOWN: site + " https://github.com/" } }); + assert.equal(both.status, 0, both.stderr); + assert.equal(readFileSync(join(both.bin, "magpie"), "utf8"), both.payload); + assert.deepEqual(both.requests.trim().split("\n").slice(1), [ + site + "vtest/magpie-cli-linux-arm64", + gh, + "https://api.github.com/repos/yetone/magpie-releases/releases/tags/vtest", + "https://api.github.com/repos/yetone/magpie-releases/releases/assets/700", + ]); +}); + +test("a mirror is put before github.com's address, never the site's, and the API isn't asked through one", (t) => { + const site = "https://usemagpie.ai/files/vtest/magpie-cli-linux-arm64"; + const m = "https://gh.mirror.example/https://github.com/yetone/magpie-releases/releases/download/vtest/magpie-cli-linux-arm64"; + const ok = install(t, { termux: false, r2: true, args: ["--mirror", "https://gh.mirror.example/"] }); + assert.equal(ok.status, 0, ok.stderr); + assert.deepEqual(ok.requests.trim().split("\n").slice(1), [site]); + const r = install(t, { termux: false, r2: true, api: true, args: ["--mirror", "https://gh.mirror.example/"], env: { INSTALL_DOWN: "https://usemagpie.ai/files/" } }); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(r.requests.trim().split("\n").slice(1), [site, m]); + assert.match(r.stdout, /from github\.com through https:\/\/gh\.mirror\.example\/ instead/); + // the mirror's bytes refused as the mirror's + const bad = install(t, { termux: false, r2: true, args: ["--mirror", "https://gh.mirror.example/"], tamper: "https://gh.mirror.example/", env: { INSTALL_DOWN: "https://usemagpie.ai/files/" } }); + assert.notEqual(bad.status, 0); + assert.match(bad.stderr, /from https:\/\/gh\.mirror\.example\/ does not match its checksum/); + const down = install(t, { termux: false, r2: true, api: true, args: ["--mirror", "https://gh.mirror.example/"], env: { INSTALL_DOWN: "https://usemagpie.ai/files/ https://gh.mirror.example/" } }); + assert.notEqual(down.status, 0); + assert.match(down.stderr, /could not download https:\/\/gh\.mirror\.example\//); + assert.doesNotMatch(down.requests, /api\.github\.com/); +}); diff --git a/site/public/install.sh b/site/public/install.sh index cd9cd7ce0..ae5833fb1 100644 --- a/site/public/install.sh +++ b/site/public/install.sh @@ -148,34 +148,52 @@ fetch() { entry=$(printf '%s' "$feed" | sed -n "s/.*\"$file\":{\([^}]*\)}.*/\1/p") url=$(printf '%s' "$entry" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p') api=$(printf '%s' "$entry" | sed -n 's/.*"api":"\([^"]*\)".*/\1/p') + # github: the file's github.com address when url is the site's copy (R2) + github=$(printf '%s' "$entry" | sed -n 's/.*"github":"\([^"]*\)".*/\1/p') sum=$(printf '%s' "$entry" | sed -n 's/.*"sha256":"\([^"]*\)".*/\1/p') version=$(printf '%s' "$feed" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p') if [ "$os" = android ] && { [ -z "$url" ] || [ -z "$sum" ]; }; then die "the newest release has no $file; build in Termux with go build -tags nogui (see $site/docs/start)" fi [ -n "$url" ] && [ -n "$sum" ] || die "the newest release has no $file" + case "$url" in https://github.com/*) github=$url ;; esac - from=$url + # The tries, in order: url (the site's copy, or github.com's own); + # github.com's address, through the mirror when one is given (a mirror + # is only ever put before a github.com address); GitHub's API, never + # through a mirror. via is the mirror a try went through. + from=$url via= case "$url" in - https://github.com/*) [ -z "$mirror" ] || from="$mirror$url" ;; + https://github.com/*) [ -z "$mirror" ] || { from="$mirror$url" via=$mirror; } ;; esac - if [ "$from" != "$url" ]; then say "downloading magpie $version ($file) through $mirror" + if [ -n "$via" ]; then say "downloading magpie $version ($file) through $mirror" else say "downloading magpie $version ($file)"; fi if ! get -o "$tmp/$file" "$from"; then - # github.com's download address can fail (504 on every try, for hours - # on 2026-11-08) while GitHub's API serves the same file: asked for - # there, checked against the same SHA-256 below. A mirror given keeps - # precedence: through one, nothing else is tried. - [ "$from" = "$url" ] || die "could not download $from" - [ -n "$api" ] || api=$(apiroute "$url" "$file") - [ -n "$api" ] || die "could not download $url" - say "that failed; downloading it through GitHub's API instead" - get -H 'Accept: application/octet-stream' -o "$tmp/$file" "$api" || die "could not download $url, nor through $api" + if [ -z "$via" ] && [ -n "$github" ] && [ "$github" != "$url" ]; then + from=$github + [ -z "$mirror" ] || { from="$mirror$github" via=$mirror; } + say "that failed; downloading it from github.com${via:+ through $via} instead" + get -o "$tmp/$file" "$from" || from= + else + from= + fi + if [ -z "$from" ]; then + # github.com's download address can fail (504 on every try, for + # hours on 2026-11-08) while GitHub's API serves the same file: + # asked for there, checked against the same SHA-256 below. A mirror + # given keeps precedence: through one, the API is never asked. + [ -z "$mirror" ] || die "could not download $mirror${github:-$url}" + [ -n "$api" ] || api=$(apiroute "${github:-$url}" "$file") + [ -n "$api" ] || die "could not download $url" + say "that failed; downloading it through GitHub's API instead" + get -H 'Accept: application/octet-stream' -o "$tmp/$file" "$api" || die "could not download $url, nor through $api" + via= + fi fi if command -v sha256sum >/dev/null; then got=$(sha256sum "$tmp/$file" | cut -d' ' -f1) else got=$(shasum -a 256 "$tmp/$file" | cut -d' ' -f1); fi if [ "$got" != "$sum" ]; then - [ "$from" = "$url" ] || die "$file from $mirror does not match its checksum from $site; not installed" + [ -z "$via" ] || die "$file from $via does not match its checksum from $site; not installed" die "$file does not match its checksum" fi }