package runtime import ( "bytes" "context" "crypto/sha256" "encoding/hex" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" ) type fakeGitHub struct { srv *httptest.Server archive []byte sums string hits map[string]int } func newFakeGitHub(t *testing.T) *fakeGitHub { t.Helper() g := &fakeGitHub{archive: bytes.Repeat([]byte("reims-runtime-"), 50_000), hits: map[string]int{}} sum := sha256.Sum256(g.archive) g.sums = hex.EncodeToString(sum[:]) + " reims-runtime-win-x64-abc1234.tar.zst\n" mux := http.NewServeMux() mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("User-Agent") != "reims-go" { t.Errorf("User-Agent = %q", r.Header.Get("User-Agent")) } base := g.srv.URL fmt.Fprintf(w, `[ {"tag_name":"runtime-abc1234","prerelease":true,"published_at":"2026-11-28T10:00:00Z","assets":[ {"name":"reims-runtime-win-x64-abc1234.tar.zst","size":%d,"browser_download_url":"%s/a/archive"}, {"name":"reims-runtime-src-abc1234.tar.zst","size":5,"browser_download_url":"%s/a/src"}, {"name":"SHA256SUMS.txt","size":90,"browser_download_url":"%s/a/sums"}]}, {"tag_name":"runtime-0000old","prerelease":false,"published_at":"2026-10-01T00:00:00Z","assets":[ {"name":"reims-runtime-win-x64-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"}, {"name":"reims-runtime-src-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"}, {"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]}, {"tag_name":"runtime-nosrc00","prerelease":false,"published_at":"2026-11-01T00:00:00Z","assets":[ {"name":"reims-runtime-win-x64-nosrc00.tar.zst","size":1,"browser_download_url":"%s/a/x"}, {"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]}, {"tag_name":"runtime-draft00","draft":true,"assets":[]}, {"tag_name":"v0.1.0","prerelease":false,"assets":[]} ]`, len(g.archive), base, base, base, base, base, base, base, base) }) mux.HandleFunc("/a/archive", func(w http.ResponseWriter, r *http.Request) { g.hits["archive"]++ if r.Header.Get("Range") != "" { g.hits["range"]++ } http.ServeContent(w, r, "a.tar.zst", time.Time{}, bytes.NewReader(g.archive)) }) mux.HandleFunc("/a/sums", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, g.sums) }) g.srv = httptest.NewServer(mux) t.Cleanup(g.srv.Close) return g } func (g *fakeGitHub) source() Source { return Source{APIBase: g.srv.URL, Repo: "o/r", Client: g.srv.Client()} } func TestDefaultSourceRepository(t *testing.T) { t.Setenv("REIMS_GO_RUNTIME_RELEASES_REPO", "") t.Setenv("REIMS_GO_RELEASES_REPO", "example/app") // app updates only if got := DefaultSource().Repo; got != "reims-go/reims-vgpu" { t.Fatalf("default runtime repository = %q", got) } t.Setenv("REIMS_GO_RUNTIME_RELEASES_REPO", "example/runtime") if got := DefaultSource().Repo; got != "example/runtime" { t.Fatalf("overridden runtime repository = %q", got) } } func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) { g := newFakeGitHub(t) stable, err := g.source().ListRemote(context.Background(), false) if err != nil { t.Fatal(err) } if len(stable) != 1 || stable[0].Commit != "0000old" || stable[0].Channel != ChannelStable { t.Fatalf("stable only = %+v", stable) } all, err := g.source().ListRemote(context.Background(), true) if err != nil { t.Fatal(err) } if len(all) != 2 || all[0].Commit != "abc1234" || all[0].Channel != ChannelAlpha || all[0].SourceName == "" { t.Fatalf("with alpha = %+v", all) } if r, err := Pick(all, "abc"); err != nil || r.Commit != "abc1234" { t.Fatalf("pick prefix: %v %v", r, err) } if r, _ := Pick(all, "latest"); r.Commit != "abc1234" { t.Fatalf("latest = %v", r) } if _, err := Pick(nil, ""); err == nil { t.Fatal("empty list") } } func TestDownloadResumesAndVerifies(t *testing.T) { g := newFakeGitHub(t) src := g.source() list, _ := src.ListRemote(context.Background(), true) r := list[0] dir := t.TempDir() // A previous run left the first 100 KB. part := filepath.Join(dir, r.ArchiveName+".part") os.WriteFile(part, g.archive[:100_000], 0o644) var last int64 path, err := src.Download(context.Background(), r, dir, func(done, total int64) { if total != int64(len(g.archive)) { t.Errorf("total = %d", total) } last = done }) if err != nil { t.Fatal(err) } if g.hits["range"] != 1 { t.Fatalf("expected a ranged request, hits=%v", g.hits) } if last != int64(len(g.archive)) { t.Fatalf("last progress = %d", last) } got, _ := os.ReadFile(path) if !bytes.Equal(got, g.archive) { t.Fatal("archive content differs") } if _, err := os.Stat(part); !os.IsNotExist(err) { t.Fatal(".part left behind") } // Already there and valid: no new request. before := g.hits["archive"] if _, err := src.Download(context.Background(), r, dir, nil); err != nil { t.Fatal(err) } if g.hits["archive"] != before { t.Fatal("re-downloaded a verified archive") } } func TestDownloadRejectsAWrongChecksum(t *testing.T) { g := newFakeGitHub(t) g.sums = strings.Repeat("0", 64) + " reims-runtime-win-x64-abc1234.tar.zst\n" list, _ := g.source().ListRemote(context.Background(), true) dir := t.TempDir() _, err := g.source().Download(context.Background(), list[0], dir, nil) if err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") { t.Fatalf("err = %v", err) } entries, _ := os.ReadDir(dir) if len(entries) != 0 { t.Fatalf("bad download kept: %v", entries) } } func TestListRemoteFollowsPagination(t *testing.T) { mux := http.NewServeMux() var srv *httptest.Server release := func(commit string, pre bool) string { return fmt.Sprintf(`{"tag_name":"runtime-%[1]s","prerelease":%[2]t,"published_at":"2026-11-%[3]sT00:00:00Z","assets":[ {"name":"reims-runtime-win-x64-%[1]s.tar.zst","size":1,"browser_download_url":"x"}, {"name":"reims-runtime-src-%[1]s.tar.zst","size":1,"browser_download_url":"x"}, {"name":"SHA256SUMS.txt","size":1,"browser_download_url":"x"}]}`, commit, pre, commit[:2]) } mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { switch r.URL.Query().Get("page") { case "": w.Header().Set("Link", fmt.Sprintf(`<%s/repos/o/r/releases?per_page=100&page=2>; rel="next", <%s/repos/o/r/releases?per_page=100&page=2>; rel="last"`, srv.URL, srv.URL)) fmt.Fprint(w, "["+release("20alpha", true)+"]") case "2": // The stable runtime sits on the second page, behind newer alphas. fmt.Fprint(w, "["+release("10stabl", false)+"]") default: t.Errorf("unexpected page %q", r.URL.RawQuery) } }) srv = httptest.NewServer(mux) defer srv.Close() src := Source{APIBase: srv.URL, Repo: "o/r", Client: srv.Client()} list, err := src.ListRemote(context.Background(), false) if err != nil { t.Fatal(err) } if len(list) != 1 || list[0].Commit != "10stabl" { t.Fatalf("stable across pages = %+v", list) } } func TestNextLinkStaysOnAPIHost(t *testing.T) { if got := nextLink(`; rel="next", ; rel="last"`); got != "https://api.github.com/x?page=2" { t.Fatalf("nextLink = %q", got) } if got := nextLink(`; rel="last"`); got != "" { t.Fatalf("no next: %q", got) } } func TestNormalizeChannel(t *testing.T) { for in, want := range map[string]string{"": ChannelStable, "stable": ChannelStable, "alpha": ChannelAlpha, "candidate": ChannelAlpha, " Alpha ": ChannelAlpha, "beta": ChannelStable} { if got := NormalizeChannel(in); got != want { t.Errorf("NormalizeChannel(%q) = %q, want %q", in, got, want) } } } func TestSameRuntimeIDDistinguishesPatchRevisions(t *testing.T) { cases := []struct { a, b string want bool }{ {"3731afd", "3731afd", true}, {"3731afd", "3731afd9b134", true}, {"3731afd", "3731afd-p2", false}, {"3731afd-p2", "3731afd", false}, {"3731afd-p2", "3731afd-p2", true}, {"3731afd-p2", "3731afd-p3", false}, {"3731afd-p2", "3731afd9b134-p2", true}, } for _, tc := range cases { if got := sameRuntimeID(tc.a, tc.b); got != tc.want { t.Errorf("sameRuntimeID(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want) } } list := []Remote{ {Commit: "3731afd-p2", Channel: ChannelAlpha}, {Commit: "3731afd", Channel: ChannelStable}, } if r, err := Pick(list, "3731afd-p2"); err != nil || r.Commit != "3731afd-p2" { t.Fatalf("Pick(-p2) = %+v, %v", r, err) } if r, err := Pick(list, "3731afd"); err != nil || r.Commit != "3731afd" { t.Fatalf("Pick(base) = %+v, %v", r, err) } if r, err := Pick(list, "latest"); err != nil || r.Commit != "3731afd-p2" { t.Fatalf("Pick(latest) = %+v, %v", r, err) } } func TestListRemoteFallsBackToWebOnRateLimit(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { http.Error(w, "API rate limit exceeded", http.StatusForbidden) }) mux.HandleFunc("/o/r/releases.atom", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, ` Portable Runtime runtime-3731afd-p2 (alpha) 2026-11-29T08:00:00Z Runtime 3731afd 2026-11-28T11:00:00Z Reims-Go v0.2.4 2026-11-29T07:00:00Z `) }) mux.HandleFunc("/o/r/releases/tag/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `Pre-release`) }) mux.HandleFunc("/o/r/releases/tag/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `Latest`) }) mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `a b c`) }) mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `a b c`) }) srv := httptest.NewServer(mux) defer srv.Close() src := Source{APIBase: srv.URL, WebBase: srv.URL, Repo: "o/r", Client: srv.Client()} stable, err := src.ListRemote(context.Background(), false) if err != nil { t.Fatal(err) } if len(stable) != 1 || stable[0].Commit != "3731afd" || stable[0].Channel != ChannelStable { t.Fatalf("stable fallback = %+v", stable) } all, err := src.ListRemote(context.Background(), true) if err != nil { t.Fatal(err) } if len(all) != 2 || all[0].Commit != "3731afd-p2" || all[0].Channel != ChannelAlpha { t.Fatalf("all fallback = %+v", all) } } func TestListRemoteWebFailsClosedAndSortsTimezones(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { http.Error(w, "API rate limit exceeded", http.StatusForbidden) }) mux.HandleFunc("/o/r/releases.atom", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, ` Runtime unverified1 2026-11-30T10:00:00Z Runtime older-tz 2026-11-29T12:00:00+08:00 Runtime newer-utc 2026-11-29T08:00:00Z `) }) // Tag page for runtime-unverif fails: must fail closed (never exposed as stable). mux.HandleFunc("/o/r/releases/tag/runtime-unverif", func(w http.ResponseWriter, r *http.Request) { http.Error(w, "temporary error", http.StatusBadGateway) }) mux.HandleFunc("/o/r/releases/tag/runtime-oldertz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `Latest`) }) mux.HandleFunc("/o/r/releases/tag/runtime-newerut", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `Latest`) }) for _, commit := range []string{"unverif", "oldertz", "newerut"} { c := commit mux.HandleFunc("/o/r/releases/expanded_assets/runtime-"+c, func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `a b c`, c, c, c, c, c) }) } srv := httptest.NewServer(mux) defer srv.Close() src := Source{APIBase: srv.URL, WebBase: srv.URL, Repo: "o/r", Client: srv.Client()} stable, err := src.ListRemote(context.Background(), false) if err != nil { t.Fatal(err) } if len(stable) != 2 { t.Fatalf("stable count = %d, want 2 (unverified tag must fail closed): %+v", len(stable), stable) } // 2026-11-29T08:00:00Z (08:00 UTC) is newer than 2026-11-29T12:00:00+08:00 (04:00 UTC). if stable[0].Commit != "newerut" || stable[1].Commit != "oldertz" { t.Fatalf("timezone sort order = [%s, %s], want [newerut, oldertz]", stable[0].Commit, stable[1].Commit) } all, err := src.ListRemote(context.Background(), true) if err != nil { t.Fatal(err) } if len(all) != 3 || all[0].Commit != "unverif" || all[0].Channel != ChannelAlpha { t.Fatalf("alpha fallback = %+v", all) } }