509 lines
14 KiB
Go
509 lines
14 KiB
Go
package runtime
|
|
|
|
// Online install reads runtime packages tagged "runtime-<commit>" from the
|
|
// Reims vGPU fork's GitHub Releases (archive, matching source archive, and
|
|
// SHA256SUMS.txt). GitHub prereleases map to the alpha channel; full releases
|
|
// map to the stable channel.
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/fetch"
|
|
"github.com/Nwflower/reims-go/internal/netproxy"
|
|
)
|
|
|
|
const (
|
|
DefaultReleasesRepo = "reims-go/reims-vgpu"
|
|
fallbackReleasesRepo = "Nwflower/Reims-Go"
|
|
DefaultAPIBase = "https://api.github.com"
|
|
DefaultWebBase = "https://github.com"
|
|
runtimeTagPrefix = "runtime-"
|
|
sumsAsset = fetch.SumsAsset
|
|
)
|
|
|
|
var errRateLimited = errors.New("GitHub API rate limit reached")
|
|
|
|
const (
|
|
ChannelStable = "stable"
|
|
ChannelAlpha = "alpha"
|
|
// channelLegacyCandidate is the legacy alias for alpha stored in older configs and manifests.
|
|
channelLegacyCandidate = "candidate"
|
|
)
|
|
|
|
// NormalizeChannel maps a stored or user-given channel name to ChannelStable
|
|
// or ChannelAlpha ("candidate" maps to alpha; empty or unknown maps to 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_RUNTIME_RELEASES_REPO
|
|
// overrides the repository (for forks and testing).
|
|
type Source struct {
|
|
APIBase string
|
|
WebBase string
|
|
Repo string
|
|
Client *http.Client
|
|
}
|
|
|
|
// DefaultSource returns the default GitHub runtime source.
|
|
func DefaultSource() Source {
|
|
repo := os.Getenv("REIMS_GO_RUNTIME_RELEASES_REPO")
|
|
if repo == "" {
|
|
repo = DefaultReleasesRepo
|
|
}
|
|
return Source{
|
|
APIBase: DefaultAPIBase,
|
|
WebBase: DefaultWebBase,
|
|
Repo: repo,
|
|
Client: netproxy.NewClient(),
|
|
}
|
|
}
|
|
|
|
// 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"`
|
|
Name string `json:"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"`
|
|
}
|
|
|
|
// isAlphaRelease treats either an explicit prerelease flag or an "(alpha)" /
|
|
// "(candidate)" marker in the release title as alpha.
|
|
func isAlphaRelease(prerelease bool, name string) bool {
|
|
if prerelease {
|
|
return true
|
|
}
|
|
lower := strings.ToLower(name)
|
|
return strings.Contains(lower, "(alpha)") || strings.Contains(lower, "(candidate)")
|
|
}
|
|
|
|
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) {
|
|
return fetch.NewRequest(ctx, url)
|
|
}
|
|
|
|
func (s Source) webBase() string {
|
|
if s.WebBase != "" {
|
|
return strings.TrimRight(s.WebBase, "/")
|
|
}
|
|
if strings.TrimRight(s.APIBase, "/") == DefaultAPIBase {
|
|
return DefaultWebBase
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// ListRemote lists published runtime packages, newest first. Alpha runtimes
|
|
// are included only when includeAlpha is set. If the default repository cannot
|
|
// be listed, it tries the original Reims-Go releases repository.
|
|
func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) {
|
|
list, err := s.listRemote(ctx, includeAlpha)
|
|
if err == nil || s.Repo != DefaultReleasesRepo || ctx.Err() != nil {
|
|
return list, err
|
|
}
|
|
|
|
fallback := s
|
|
fallback.Repo = fallbackReleasesRepo
|
|
list, fallbackErr := fallback.listRemote(ctx, includeAlpha)
|
|
if fallbackErr != nil {
|
|
return nil, fmt.Errorf("%s: %w; %s: %w", s.Repo, err, fallback.Repo, fallbackErr)
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
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 {
|
|
if errors.Is(err, errRateLimited) && 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,
|
|
PublishedAt: pub,
|
|
PageURL: pageURL,
|
|
Channel: ChannelStable,
|
|
}
|
|
if isAlphaRelease(r.Prerelease, r.Name) {
|
|
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 := ChannelAlpha
|
|
if tagHTML, err := s.fetchText(ctx, tagURL, "text/html"); err == nil {
|
|
if !isAlphaRelease(rePrereleaseBadge.MatchString(tagHTML), e.Title) {
|
|
channel = ChannelStable
|
|
}
|
|
}
|
|
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,
|
|
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)
|
|
}
|
|
sortRemotesNewestFirst(out)
|
|
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 = fetch.Progress
|
|
|
|
// 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) {
|
|
want, err := fetch.ExpectedSum(ctx, s.client(), r.SumsURL, r.ArchiveName)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return "", err
|
|
}
|
|
return fetch.Resume(ctx, s.client(), r.ArchiveURL, filepath.Join(dir, r.ArchiveName), r.ArchiveSize, want, onProgress)
|
|
}
|
|
|
|
// 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, ""
|
|
}
|
|
|
|
var suspendReleaseIDPattern = regexp.MustCompile(`^[0-9a-f]{7,40}(-p[1-9][0-9]*)?$`)
|
|
|
|
// SuspendCompatibilityID accepts a declaration only for its own release family.
|
|
// An absent declaration keeps the legacy exact-runtime checks.
|
|
func SuspendCompatibilityID(releaseID, declared string) string {
|
|
releaseID = strings.ToLower(strings.TrimSpace(releaseID))
|
|
declared = strings.ToLower(strings.TrimSpace(declared))
|
|
base, _ := splitRuntimeID(releaseID)
|
|
if !suspendReleaseIDPattern.MatchString(releaseID) || declared != base {
|
|
return ""
|
|
}
|
|
return declared
|
|
}
|
|
|
|
// 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
|
|
}
|