Files
Reims-Go/internal/runtime/remote.go
T

718 lines
20 KiB
Go

package runtime
// Online install: runtime packages are GitHub Release assets of the reims-go
// repository (decided 2026-11-28, AGENTS.md). A runtime release is tagged
// "runtime-<commit>" and carries:
//
// reims-runtime-win-x64-<commit>.tar.zst
// reims-runtime-src-<commit>.tar.zst (matching sources, spec §7)
// SHA256SUMS.txt
//
// A GitHub prerelease is the alpha channel (built automatically from upstream
// by CI); a full release is stable (promoted by a person after a real-host
// smoke test, spec §6). The client lists stable only unless alpha is asked for.
import (
"bufio"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/netproxy"
)
const (
DefaultReleasesRepo = "Nwflower/reims-go"
DefaultAPIBase = "https://api.github.com"
DefaultWebBase = "https://github.com"
DefaultGitCodeRepo = "Nwflower/Reims-Go"
DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5"
DefaultGitCodeWebBase = "https://gitcode.com"
runtimeTagPrefix = "runtime-"
sumsAsset = "SHA256SUMS.txt"
)
const (
SourceAuto = "auto"
SourceGitHub = "github"
SourceGitCode = "gitcode"
)
// NormalizeSource maps a stored or user-given source name to SourceAuto,
// SourceGitHub, or SourceGitCode. Empty or unknown values default to SourceAuto.
func NormalizeSource(s string) string {
switch strings.ToLower(strings.TrimSpace(s)) {
case SourceGitHub:
return SourceGitHub
case SourceGitCode:
return SourceGitCode
default:
return SourceAuto
}
}
var errRateLimited = errors.New("GitHub API rate limit reached")
const (
ChannelStable = "stable"
ChannelAlpha = "alpha"
// channelLegacyCandidate is what the alpha channel was called before
// 2026-11-28; configs and manifests written then still say it.
channelLegacyCandidate = "candidate"
)
// NormalizeChannel maps a stored or user-given channel name to ChannelStable
// or ChannelAlpha. The pre-2026-11-28 name "candidate" means alpha; anything
// else (including "") means stable.
func NormalizeChannel(s string) string {
switch strings.ToLower(strings.TrimSpace(s)) {
case ChannelAlpha, channelLegacyCandidate:
return ChannelAlpha
}
return ChannelStable
}
// maxReleasePages bounds how far ListRemote follows GitHub's pagination: the
// releases API returns at most 100 per page, and the repository also holds
// app releases and (until pruned) daily alpha runtimes.
const maxReleasePages = 10
// fallbackProbeTimeout bounds how long a primary source query may block when a
// mirror fallback is configured, so unreachable hosts fail over quickly.
const fallbackProbeTimeout = 8 * time.Second
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO and
// REIMS_GO_GITCODE_REPO override the repositories (for forks and testing).
type Source struct {
Provider string
APIBase string
WebBase string
Repo string
Client *http.Client
Fallbacks []Source
}
func githubSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{
Provider: SourceGitHub,
APIBase: DefaultAPIBase,
WebBase: DefaultWebBase,
Repo: repo,
Client: client,
}
}
func gitcodeSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_GITCODE_REPO")
if repo == "" {
repo = DefaultGitCodeRepo
}
return Source{
Provider: SourceGitCode,
APIBase: DefaultGitCodeAPIBase,
WebBase: DefaultGitCodeWebBase,
Repo: repo,
Client: client,
}
}
// DefaultSource returns the default runtime source (SourceAuto unless
// REIMS_GO_SOURCE overrides it).
func DefaultSource() Source {
return DefaultSourceFor("")
}
// DefaultSourceFor returns a Source configured for mode ("auto", "github", or
// "gitcode"). When mode is empty, REIMS_GO_SOURCE is consulted before falling
// back to "auto" (GitHub primary, GitCode fallback).
func DefaultSourceFor(mode string) Source {
if strings.TrimSpace(mode) == "" {
mode = os.Getenv("REIMS_GO_SOURCE")
}
client := netproxy.NewClient()
switch NormalizeSource(mode) {
case SourceGitHub:
return githubSource(client)
case SourceGitCode:
return gitcodeSource(client)
default:
gh := githubSource(client)
gh.Fallbacks = []Source{gitcodeSource(client)}
return gh
}
}
// Remote is a runtime package published as a release.
type Remote struct {
Commit string `json:"commit"`
Tag string `json:"tag"`
Channel string `json:"channel"`
Source string `json:"source,omitempty"`
PublishedAt string `json:"published_at"`
PageURL string `json:"page_url"`
ArchiveName string `json:"archive_name"`
ArchiveURL string `json:"archive_url"`
ArchiveSize int64 `json:"archive_size"`
SumsURL string `json:"sums_url"`
SourceName string `json:"source_name,omitempty"`
SourceURL string `json:"source_url,omitempty"`
}
type ghRelease struct {
TagName string `json:"tag_name"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
CreatedAt string `json:"created_at"`
HTMLURL string `json:"html_url"`
Assets []ghAsset `json:"assets"`
}
type ghAsset struct {
Name string `json:"name"`
Size int64 `json:"size"`
URL string `json:"browser_download_url"`
}
func (s Source) client() *http.Client {
if s.Client != nil {
return s.Client
}
return http.DefaultClient
}
func newRequest(ctx context.Context, url string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
// A generic client name; nothing about the user (GitHub requires a User-Agent).
req.Header.Set("User-Agent", "reims-go")
if req.URL.Host == "api.github.com" {
if tok := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
} else if tok := strings.TrimSpace(os.Getenv("GH_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
return req, nil
}
func (s Source) providerName() string {
if s.Provider != "" {
return s.Provider
}
if strings.Contains(strings.ToLower(s.APIBase), "gitcode.com") {
return SourceGitCode
}
return SourceGitHub
}
func (s Source) webBase() string {
if s.WebBase != "" {
return strings.TrimRight(s.WebBase, "/")
}
if strings.TrimRight(s.APIBase, "/") == DefaultAPIBase {
return DefaultWebBase
}
if strings.TrimRight(s.APIBase, "/") == DefaultGitCodeAPIBase {
return DefaultGitCodeWebBase
}
return ""
}
// ListRemote lists published runtime packages, newest first. Alpha runtimes
// are included only when includeAlpha is set. When Fallbacks are configured,
// a failing primary source automatically fails over to the next mirror.
func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) {
primaryCtx := ctx
var cancel context.CancelFunc
if len(s.Fallbacks) > 0 {
primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout)
defer cancel()
}
out, err := s.listRemoteSingle(primaryCtx, includeAlpha)
if err == nil {
return out, nil
}
if ctx.Err() != nil || len(s.Fallbacks) == 0 {
return nil, err
}
var lastErr error
for _, fb := range s.Fallbacks {
fbOut, fbErr := fb.listRemoteSingle(ctx, includeAlpha)
if fbErr == nil {
return fbOut, nil
}
lastErr = fbErr
}
return nil, fmt.Errorf("%w (mirror fallback failed: %v)", err, lastErr)
}
func (s Source) listRemoteSingle(ctx context.Context, includeAlpha bool) ([]Remote, error) {
base := strings.TrimRight(s.APIBase, "/")
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo)
provider := s.providerName()
var rels []ghRelease
for page := 0; url != "" && page < maxReleasePages; page++ {
batch, next, err := s.releasesPage(ctx, url)
if err != nil {
if errors.Is(err, errRateLimited) && provider == SourceGitHub && s.webBase() != "" {
if fb, ferr := s.listRemoteWeb(ctx, includeAlpha); ferr == nil {
return fb, nil
}
}
return nil, err
}
rels = append(rels, batch...)
// Follow only links back to the same API (never another host).
if !strings.HasPrefix(next, base+"/") {
next = ""
}
url = next
}
var out []Remote
for _, r := range rels {
if r.Draft || !strings.HasPrefix(r.TagName, runtimeTagPrefix) {
continue
}
commit := strings.TrimPrefix(r.TagName, runtimeTagPrefix)
pub := r.PublishedAt
if pub == "" {
pub = r.CreatedAt
}
pageURL := r.HTMLURL
if pageURL == "" && s.webBase() != "" {
pageURL = fmt.Sprintf("%s/%s/releases/tag/%s", s.webBase(), s.Repo, r.TagName)
}
rem := Remote{
Commit: commit,
Tag: r.TagName,
Source: provider,
PublishedAt: pub,
PageURL: pageURL,
Channel: ChannelStable,
}
if r.Prerelease {
rem.Channel = ChannelAlpha
}
for _, a := range r.Assets {
switch {
case a.Name == "reims-runtime-win-x64-"+commit+".tar.zst":
rem.ArchiveName, rem.ArchiveURL, rem.ArchiveSize = a.Name, a.URL, a.Size
case a.Name == sumsAsset:
rem.SumsURL = a.URL
case strings.HasPrefix(a.Name, "reims-runtime-src-"):
rem.SourceName, rem.SourceURL = a.Name, a.URL
}
}
// A release without its sums or sources is incomplete: never offer it.
if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" {
continue
}
if rem.Channel == ChannelAlpha && !includeAlpha {
continue
}
out = append(out, rem)
}
sortRemotesNewestFirst(out)
return out, nil
}
func sortRemotesNewestFirst(out []Remote) {
sort.SliceStable(out, func(i, j int) bool {
ti, ei := time.Parse(time.RFC3339, out[i].PublishedAt)
tj, ej := time.Parse(time.RFC3339, out[j].PublishedAt)
if ei == nil && ej == nil && !ti.Equal(tj) {
return ti.After(tj)
}
return out[i].PublishedAt > out[j].PublishedAt
})
}
// releasesPage fetches one page of the releases API and returns the URL of
// the next page from the Link header ("" on the last page).
func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, string, error) {
req, err := newRequest(ctx, url)
if err != nil {
return nil, "", err
}
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := s.client().Do(req)
if err != nil {
return nil, "", fmt.Errorf("list runtime releases: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return nil, "", fmt.Errorf("%w; try again later (HTTP %d)", errRateLimited, resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode)
}
var rels []ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil {
return nil, "", fmt.Errorf("read runtime releases: %w", err)
}
return rels, nextLink(resp.Header.Get("Link")), nil
}
type atomFeed struct {
Entries []atomEntry `xml:"entry"`
}
type atomEntry struct {
Title string `xml:"title"`
Updated string `xml:"updated"`
Links []atomLink `xml:"link"`
}
type atomLink struct {
Rel string `xml:"rel,attr"`
Href string `xml:"href,attr"`
}
var (
reExpandedAssetHref = regexp.MustCompile(`href="(/[^"]+/releases/download/[^"]+)"`)
rePrereleaseBadge = regexp.MustCompile(`(?i)>\s*Pre-release\s*<`)
)
// listRemoteWeb reads runtime releases from GitHub's public Atom feed and
// expanded_assets fragments, which do not consume api.github.com's 60 req/hr
// unauthenticated IP quota.
func (s Source) listRemoteWeb(ctx context.Context, includeAlpha bool) ([]Remote, error) {
web := s.webBase()
atomURL := fmt.Sprintf("%s/%s/releases.atom", web, s.Repo)
body, err := s.fetchText(ctx, atomURL, "application/atom+xml, application/xml")
if err != nil {
return nil, err
}
var feed atomFeed
if err := xml.Unmarshal([]byte(body), &feed); err != nil {
return nil, fmt.Errorf("parse releases.atom: %w", err)
}
var out []Remote
for _, e := range feed.Entries {
var pageURL string
for _, l := range e.Links {
if l.Rel == "" || l.Rel == "alternate" {
pageURL = l.Href
break
}
}
idx := strings.LastIndex(pageURL, "/releases/tag/")
if idx < 0 {
continue
}
tag := pageURL[idx+len("/releases/tag/"):]
if !strings.HasPrefix(tag, runtimeTagPrefix) {
continue
}
commit := strings.TrimPrefix(tag, runtimeTagPrefix)
tagURL := fmt.Sprintf("%s/%s/releases/tag/%s", web, s.Repo, tag)
channel := ChannelStable
if tagHTML, err := s.fetchText(ctx, tagURL, "text/html"); err == nil {
if rePrereleaseBadge.MatchString(tagHTML) {
channel = ChannelAlpha
}
} else if strings.Contains(strings.ToLower(e.Title), "(alpha)") {
channel = ChannelAlpha
}
if channel == ChannelAlpha && !includeAlpha {
continue
}
expURL := fmt.Sprintf("%s/%s/releases/expanded_assets/%s", web, s.Repo, tag)
expHTML, err := s.fetchText(ctx, expURL, "text/html")
if err != nil {
continue
}
rem := Remote{
Commit: commit,
Tag: tag,
Channel: channel,
Source: SourceGitHub,
PublishedAt: e.Updated,
PageURL: pageURL,
}
for _, m := range reExpandedAssetHref.FindAllStringSubmatch(expHTML, -1) {
href := m[1]
name := path.Base(href)
dl := web + href
switch {
case name == "reims-runtime-win-x64-"+commit+".tar.zst":
rem.ArchiveName, rem.ArchiveURL = name, dl
case name == sumsAsset:
rem.SumsURL = dl
case strings.HasPrefix(name, "reims-runtime-src-"):
rem.SourceName, rem.SourceURL = name, dl
}
}
if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" {
continue
}
out = append(out, rem)
}
sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt })
return out, nil
}
func (s Source) fetchText(ctx context.Context, rawURL, accept string) (string, error) {
req, err := newRequest(ctx, rawURL)
if err != nil {
return "", err
}
if accept != "" {
req.Header.Set("Accept", accept)
}
resp, err := s.client().Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("fetch %s: HTTP %d", rawURL, resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return "", err
}
return string(data), nil
}
// nextLink returns the rel="next" target of an RFC 8288 Link header.
func nextLink(h string) string {
for _, part := range strings.Split(h, ",") {
seg := strings.Split(part, ";")
if len(seg) < 2 {
continue
}
isNext := false
for _, p := range seg[1:] {
if strings.TrimSpace(p) == `rel="next"` {
isNext = true
}
}
if isNext {
return strings.Trim(strings.TrimSpace(seg[0]), "<>")
}
}
return ""
}
// Pick finds a release by exact ID, revision-matching commit prefix, or the
// newest for "" / "latest".
func Pick(list []Remote, want string) (*Remote, error) {
want = strings.TrimSpace(want)
if len(list) == 0 {
return nil, errors.New("no runtime release is published for this channel")
}
if want == "" || strings.EqualFold(want, "latest") {
return &list[0], nil
}
for i := range list {
if list[i].Commit == want {
return &list[i], nil
}
}
for i := range list {
if sameRuntimeID(list[i].Commit, want) {
return &list[i], nil
}
}
for i := range list {
if strings.HasPrefix(list[i].Commit, want) {
return &list[i], nil
}
}
return nil, fmt.Errorf("no runtime release for %q", want)
}
// Progress reports bytes of the archive download.
type Progress func(done, total int64)
// Download fetches r's archive into dir, continuing a partial download, and
// checks it against the release's SHA256SUMS.txt. It returns the archive path.
func (s Source) Download(ctx context.Context, r Remote, dir string, onProgress Progress) (string, error) {
if onProgress == nil {
onProgress = func(int64, int64) {}
}
want, err := s.expectedSum(ctx, r)
if err != nil {
return "", err
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
final := filepath.Join(dir, r.ArchiveName)
if got, err := fileSHA256(final); err == nil && strings.EqualFold(got, want) {
onProgress(r.ArchiveSize, r.ArchiveSize)
return final, nil
}
part := final + ".part"
var have int64
if st, err := os.Stat(part); err == nil {
have = st.Size()
}
req, err := newRequest(ctx, r.ArchiveURL)
if err != nil {
return "", err
}
if have > 0 {
req.Header.Set("Range", "bytes="+strconv.FormatInt(have, 10)+"-")
}
resp, err := s.client().Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", r.ArchiveName, err)
}
defer resp.Body.Close()
flags := os.O_CREATE | os.O_WRONLY
switch resp.StatusCode {
case http.StatusPartialContent:
flags |= os.O_APPEND
case http.StatusOK:
have = 0 // server ignored the range: start over
flags |= os.O_TRUNC
case http.StatusRequestedRangeNotSatisfiable:
os.Remove(part)
return s.Download(ctx, r, dir, onProgress)
default:
return "", fmt.Errorf("download %s: HTTP %d", r.ArchiveName, resp.StatusCode)
}
total := r.ArchiveSize
if total <= 0 && resp.ContentLength > 0 {
total = have + resp.ContentLength
}
f, err := os.OpenFile(part, flags, 0o644)
if err != nil {
return "", err
}
done := have
onProgress(done, total)
buf := make([]byte, 256*1024)
last := time.Now()
for {
n, rerr := resp.Body.Read(buf)
if n > 0 {
if _, werr := f.Write(buf[:n]); werr != nil {
f.Close()
return "", werr
}
done += int64(n)
if time.Since(last) > 100*time.Millisecond {
onProgress(done, total)
last = time.Now()
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
f.Close()
return "", fmt.Errorf("download %s: %w", r.ArchiveName, rerr) // .part kept for resume
}
}
if err := f.Close(); err != nil {
return "", err
}
onProgress(done, total)
got, err := fileSHA256(part)
if err != nil {
return "", err
}
if !strings.EqualFold(got, want) {
os.Remove(part)
return "", fmt.Errorf("%s: SHA256 mismatch (expected %s, got %s); the download was discarded", r.ArchiveName, want, got)
}
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
// expectedSum reads r's archive hash from the release's SHA256SUMS.txt
// ("<hex> <name>" lines, as sha256sum writes them).
func (s Source) expectedSum(ctx context.Context, r Remote) (string, error) {
req, err := newRequest(ctx, r.SumsURL)
if err != nil {
return "", err
}
resp, err := s.client().Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", sumsAsset, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download %s: HTTP %d", sumsAsset, resp.StatusCode)
}
sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20))
for sc.Scan() {
fields := strings.Fields(sc.Text())
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == r.ArchiveName && len(fields[0]) == 64 {
return strings.ToLower(fields[0]), nil
}
}
return "", fmt.Errorf("%s has no entry for %s", sumsAsset, r.ArchiveName)
}
// DownloadsDir is where runtime archives are downloaded before install.
func DownloadsDir(cfg *config.Config) string {
return filepath.Join(cfg.DataRoot, "downloads")
}
// splitRuntimeID separates "<commit>" and an optional patch-revision suffix
// such as "-p2" in "3731afd-p2".
func splitRuntimeID(id string) (base, rev string) {
if i := strings.IndexByte(id, '-'); i >= 0 {
return id[:i], id[i+1:]
}
return id, ""
}
// sameRuntimeID reports whether a and b refer to the same runtime build,
// allowing short/full commit prefix matching only within the same revision.
func sameRuntimeID(a, b string) bool {
if a == "" || b == "" {
return false
}
baseA, revA := splitRuntimeID(a)
baseB, revB := splitRuntimeID(b)
if revA != revB {
return false
}
return strings.HasPrefix(baseA, baseB) || strings.HasPrefix(baseB, baseA)
}
// IsInstalled reports whether commit is already unpacked under runtimes/.
func IsInstalled(cfg *config.Config, commit string) bool {
list, err := List(cfg)
if err != nil {
return false
}
for _, it := range list {
if sameRuntimeID(it.Commit, commit) {
return true
}
}
return false
}