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

424 lines
12 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"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
)
const (
DefaultReleasesRepo = "Nwflower/reims-go"
DefaultAPIBase = "https://api.github.com"
runtimeTagPrefix = "runtime-"
sumsAsset = "SHA256SUMS.txt"
)
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
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO
// overrides the repository (for forks and testing).
type Source struct {
APIBase string
Repo string
Client *http.Client
}
func DefaultSource() Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{APIBase: DefaultAPIBase, Repo: repo, Client: &http.Client{Timeout: 0}}
}
// Remote is a runtime package published as a release.
type Remote struct {
Commit string `json:"commit"`
Tag string `json:"tag"`
Channel string `json:"channel"`
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"`
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")
return req, nil
}
// ListRemote lists published runtime packages, newest first. Alpha runtimes
// are included only when includeAlpha is set.
func (s Source) ListRemote(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)
var rels []ghRelease
for page := 0; url != "" && page < maxReleasePages; page++ {
batch, next, err := s.releasesPage(ctx, url)
if err != 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)
rem := Remote{Commit: commit, Tag: r.TagName, PublishedAt: r.PublishedAt, PageURL: r.HTMLURL, 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)
}
sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt })
return out, nil
}
// 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("GitHub API rate limit reached; try again later (HTTP %d)", 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
}
// 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
}