fix(net): honor Windows system proxy, fall back on GitHub rate limit, and add UI retry
This commit is contained in:
1 parent
5000e00780
commit
33ac322bb2
10 files changed
+508
-8
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { Download, LoaderCircle, Pause } from 'lucide-react'
|
||||
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
@@ -29,6 +29,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [reload, setReload] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
@@ -38,7 +39,7 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
.then((list) => { if (live) setRemote(list ?? []) })
|
||||
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done'])
|
||||
}, [channel, task?.status === 'done', reload])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
@@ -63,7 +64,9 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
} else if (active && !updatable) {
|
||||
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
|
||||
} else if (error) {
|
||||
sub = <div className="row-sub" title={error}>{tr('runtimeLookupFailed')}</div>
|
||||
const isRateLimit = /rate limit|HTTP 403|HTTP 429/i.test(error)
|
||||
const msg = isRateLimit ? tr('runtimeLookupRateLimit') : `${tr('runtimeLookupFailed')}: ${error}`
|
||||
sub = <div className="row-sub" title={error}>{msg}</div>
|
||||
} else if (!remote) {
|
||||
sub = <div className="row-sub">…</div>
|
||||
} else if (!latest) {
|
||||
@@ -72,7 +75,8 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} · {gb(latest.archive_size)}
|
||||
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
|
||||
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -89,6 +93,10 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<div className="row-right">
|
||||
{running && task?.cancelable ? (
|
||||
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
|
||||
) : !running && error ? (
|
||||
<Button icon={<RefreshCw size={14} />} onClick={() => setReload((n) => n + 1)}>
|
||||
{tr('runtimeRetry')}
|
||||
</Button>
|
||||
) : !running && updatable ? (
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
|
||||
@@ -183,6 +183,8 @@ const dict = {
|
||||
runtimeChannel_alpha: 'Alpha 版',
|
||||
runtimeChannel_stable: '稳定版',
|
||||
runtimeLookupFailed: '无法读取 GitHub 上的运行时列表',
|
||||
runtimeLookupRateLimit: 'GitHub 接口限流(HTTP 403),请稍后重试、切换代理节点或手动导入运行时包',
|
||||
runtimeRetry: '重试',
|
||||
|
||||
// Toasts & dialogs
|
||||
toastStopped: '{name} 已关机',
|
||||
@@ -696,6 +698,8 @@ const dict = {
|
||||
runtimeChannel_alpha: 'Alpha',
|
||||
runtimeChannel_stable: 'Stable',
|
||||
runtimeLookupFailed: 'Couldn’t read the runtime list from GitHub',
|
||||
runtimeLookupRateLimit: 'GitHub API rate limit reached (HTTP 403); retry later, switch proxy node, or import a local bundle',
|
||||
runtimeRetry: 'Retry',
|
||||
|
||||
toastStopped: '{name} shut down',
|
||||
toastEjected: 'Installer ejected',
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
// PinnedAsset describes a file that upstream `reims-util` caches under
|
||||
@@ -180,7 +182,7 @@ func (c *idleTimeoutConn) Read(p []byte) (int, error) {
|
||||
func newIdleHTTPClient(idle time.Duration) *http.Client {
|
||||
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
|
||||
tr := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
Proxy: netproxy.ProxyFromEnvOrSystem,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
conn, err := dialer.DialContext(ctx, network, addr)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ProxyFromEnvOrSystem resolves a proxy for req, preferring standard
|
||||
// HTTP_PROXY/HTTPS_PROXY/NO_PROXY environment variables and falling back to
|
||||
// the host OS proxy settings (Windows Internet Settings registry).
|
||||
func ProxyFromEnvOrSystem(req *http.Request) (*url.URL, error) {
|
||||
if u, err := http.ProxyFromEnvironment(req); u != nil || err != nil {
|
||||
return u, err
|
||||
}
|
||||
return systemProxy(req)
|
||||
}
|
||||
|
||||
// NewTransport returns an http.Transport configured with env/OS proxy support
|
||||
// and bounded connection/header timeouts (without limiting streaming body
|
||||
// download duration).
|
||||
func NewTransport() *http.Transport {
|
||||
var tr *http.Transport
|
||||
if base, ok := http.DefaultTransport.(*http.Transport); ok {
|
||||
tr = base.Clone()
|
||||
} else {
|
||||
tr = &http.Transport{}
|
||||
}
|
||||
tr.Proxy = ProxyFromEnvOrSystem
|
||||
tr.DialContext = (&net.Dialer{
|
||||
Timeout: 20 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext
|
||||
tr.TLSHandshakeTimeout = 20 * time.Second
|
||||
tr.ResponseHeaderTimeout = 30 * time.Second
|
||||
return tr
|
||||
}
|
||||
|
||||
// NewClient returns an http.Client using NewTransport.
|
||||
func NewClient() *http.Client {
|
||||
return &http.Client{Transport: NewTransport()}
|
||||
}
|
||||
|
||||
// parseWindowsProxyServer parses Windows Internet Settings ProxyServer values:
|
||||
// either a single proxy ("127.0.0.1:7890", "http://127.0.0.1:7890") or a
|
||||
// semicolon-separated per-scheme map ("http=127.0.0.1:7890;https=127.0.0.1:7890;socks=127.0.0.1:7891").
|
||||
func parseWindowsProxyServer(server, reqScheme string) (*url.URL, error) {
|
||||
server = strings.TrimSpace(server)
|
||||
if server == "" {
|
||||
return nil, nil
|
||||
}
|
||||
reqScheme = strings.ToLower(strings.TrimSpace(reqScheme))
|
||||
if reqScheme == "" {
|
||||
reqScheme = "http"
|
||||
}
|
||||
|
||||
var chosen, chosenKey string
|
||||
if !strings.Contains(server, "=") {
|
||||
chosen = server
|
||||
} else {
|
||||
byScheme := map[string]string{}
|
||||
for _, entry := range strings.Split(server, ";") {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if entry == "" {
|
||||
continue
|
||||
}
|
||||
k, v, ok := strings.Cut(entry, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k = strings.ToLower(strings.TrimSpace(k))
|
||||
v = strings.TrimSpace(v)
|
||||
if k != "" && v != "" {
|
||||
byScheme[k] = v
|
||||
}
|
||||
}
|
||||
for _, key := range []string{reqScheme, "http", "https", "socks5", "socks"} {
|
||||
if v, ok := byScheme[key]; ok {
|
||||
chosen = v
|
||||
chosenKey = key
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if chosen == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if !strings.Contains(chosen, "://") {
|
||||
if chosenKey == "socks" || chosenKey == "socks5" {
|
||||
chosen = "socks5://" + chosen
|
||||
} else {
|
||||
// In Windows Internet Settings, "https=host:port" denotes an HTTP
|
||||
// CONNECT proxy used for HTTPS requests, not a TLS proxy endpoint.
|
||||
chosen = "http://" + chosen
|
||||
}
|
||||
}
|
||||
u, err := url.Parse(chosen)
|
||||
if err != nil || u.Host == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// shouldBypassWindowsProxy evaluates Windows ProxyOverride rules (semicolon or
|
||||
// whitespace separated patterns, including "<local>" and "*" wildcards).
|
||||
func shouldBypassWindowsProxy(override, host string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
if host == "" {
|
||||
return false
|
||||
}
|
||||
fields := strings.FieldsFunc(override, func(r rune) bool {
|
||||
return r == ';' || r == ' ' || r == '\t' || r == ','
|
||||
})
|
||||
for _, pat := range fields {
|
||||
pat = strings.ToLower(strings.TrimSpace(pat))
|
||||
if pat == "" {
|
||||
continue
|
||||
}
|
||||
if pat == "<local>" {
|
||||
if !strings.Contains(host, ".") || host == "localhost" || host == "127.0.0.1" || host == "::1" {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
// Strip optional scheme or port in Windows bypass rules (e.g. "http://*.local").
|
||||
if _, after, ok := strings.Cut(pat, "://"); ok {
|
||||
pat = after
|
||||
}
|
||||
if h, _, err := net.SplitHostPort(pat); err == nil && h != "" {
|
||||
pat = h
|
||||
}
|
||||
if pat == host {
|
||||
return true
|
||||
}
|
||||
if strings.ContainsAny(pat, "*?") {
|
||||
if matched, err := path.Match(pat, host); err == nil && matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseWindowsProxyServer(t *testing.T) {
|
||||
cases := []struct {
|
||||
server string
|
||||
scheme string
|
||||
want string
|
||||
}{
|
||||
{"127.0.0.1:7890", "https", "http://127.0.0.1:7890"},
|
||||
{"http://127.0.0.1:7890", "https", "http://127.0.0.1:7890"},
|
||||
{"socks5://127.0.0.1:7891", "https", "socks5://127.0.0.1:7891"},
|
||||
{"http=127.0.0.1:7890;https=127.0.0.1:7891", "https", "http://127.0.0.1:7891"},
|
||||
{"http=127.0.0.1:7890;https=127.0.0.1:7891", "http", "http://127.0.0.1:7890"},
|
||||
{"socks=127.0.0.1:10808", "https", "socks5://127.0.0.1:10808"},
|
||||
{"http=127.0.0.1:8080", "https", "http://127.0.0.1:8080"},
|
||||
{"", "https", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
u, err := parseWindowsProxyServer(tc.server, tc.scheme)
|
||||
if err != nil {
|
||||
t.Fatalf("parseWindowsProxyServer(%q, %q) err = %v", tc.server, tc.scheme, err)
|
||||
}
|
||||
got := ""
|
||||
if u != nil {
|
||||
got = u.String()
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Errorf("parseWindowsProxyServer(%q, %q) = %q, want %q", tc.server, tc.scheme, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldBypassWindowsProxy(t *testing.T) {
|
||||
override := "localhost;127.*;10.*;*.local;<local>"
|
||||
for host, want := range map[string]bool{
|
||||
"localhost": true,
|
||||
"127.0.0.1": true,
|
||||
"10.0.0.5": true,
|
||||
"nas.local": true,
|
||||
"intranet": true,
|
||||
"api.github.com": false,
|
||||
"github.com": false,
|
||||
} {
|
||||
if got := shouldBypassWindowsProxy(override, host); got != want {
|
||||
t.Errorf("shouldBypassWindowsProxy(%q, %q) = %v, want %v", override, host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyFromEnvTakesPrecedence(t *testing.T) {
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:19999")
|
||||
req, _ := http.NewRequest(http.MethodGet, "https://api.github.com/repos/Nwflower/reims-go/releases", nil)
|
||||
u, err := ProxyFromEnvOrSystem(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u == nil || u.String() != "http://127.0.0.1:19999" {
|
||||
t.Fatalf("got %v, want http://127.0.0.1:19999", u)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func systemProxy(*http.Request) (*url.URL, error) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build windows
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
const internetSettingsPath = `Software\Microsoft\Windows\CurrentVersion\Internet Settings`
|
||||
|
||||
func systemProxy(req *http.Request) (*url.URL, error) {
|
||||
if req == nil || req.URL == nil {
|
||||
return nil, nil
|
||||
}
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, internetSettingsPath, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
defer k.Close()
|
||||
|
||||
enabled, _, err := k.GetIntegerValue("ProxyEnable")
|
||||
if err != nil || enabled == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
server, _, err := k.GetStringValue("ProxyServer")
|
||||
if err != nil || server == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if override, _, err := k.GetStringValue("ProxyOverride"); err == nil && override != "" {
|
||||
if shouldBypassWindowsProxy(override, req.URL.Hostname()) {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return parseWindowsProxyServer(server, req.URL.Scheme)
|
||||
}
|
||||
+158
-2
@@ -16,27 +16,34 @@ 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"
|
||||
runtimeTagPrefix = "runtime-"
|
||||
sumsAsset = "SHA256SUMS.txt"
|
||||
)
|
||||
|
||||
var errRateLimited = errors.New("GitHub API rate limit reached")
|
||||
|
||||
const (
|
||||
ChannelStable = "stable"
|
||||
ChannelAlpha = "alpha"
|
||||
@@ -65,6 +72,7 @@ const maxReleasePages = 10
|
||||
// overrides the repository (for forks and testing).
|
||||
type Source struct {
|
||||
APIBase string
|
||||
WebBase string
|
||||
Repo string
|
||||
Client *http.Client
|
||||
}
|
||||
@@ -74,7 +82,12 @@ func DefaultSource() Source {
|
||||
if repo == "" {
|
||||
repo = DefaultReleasesRepo
|
||||
}
|
||||
return Source{APIBase: DefaultAPIBase, Repo: repo, Client: &http.Client{Timeout: 0}}
|
||||
return Source{
|
||||
APIBase: DefaultAPIBase,
|
||||
WebBase: DefaultWebBase,
|
||||
Repo: repo,
|
||||
Client: netproxy.NewClient(),
|
||||
}
|
||||
}
|
||||
|
||||
// Remote is a runtime package published as a release.
|
||||
@@ -121,9 +134,26 @@ func newRequest(ctx context.Context, url string) (*http.Request, error) {
|
||||
}
|
||||
// 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) 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.
|
||||
func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) {
|
||||
@@ -133,6 +163,11 @@ func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, er
|
||||
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...)
|
||||
@@ -189,7 +224,7 @@ func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, stri
|
||||
}
|
||||
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)
|
||||
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)
|
||||
@@ -201,6 +236,127 @@ func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, stri
|
||||
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,
|
||||
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, ",") {
|
||||
|
||||
@@ -235,3 +235,64 @@ func TestSameRuntimeIDDistinguishesPatchRevisions(t *testing.T) {
|
||||
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, `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom">
|
||||
<entry>
|
||||
<title>Portable Runtime runtime-3731afd-p2 (alpha)</title>
|
||||
<updated>2026-11-29T08:00:00Z</updated>
|
||||
<link rel="alternate" href="https://github.com/o/r/releases/tag/runtime-3731afd-p2"/>
|
||||
</entry>
|
||||
<entry>
|
||||
<title>Runtime 3731afd</title>
|
||||
<updated>2026-11-28T11:00:00Z</updated>
|
||||
<link rel="alternate" href="https://github.com/o/r/releases/tag/runtime-3731afd"/>
|
||||
</entry>
|
||||
<entry>
|
||||
<title>Reims-Go v0.2.4</title>
|
||||
<updated>2026-11-29T07:00:00Z</updated>
|
||||
<link rel="alternate" href="https://github.com/o/r/releases/tag/v0.2.4"/>
|
||||
</entry>
|
||||
</feed>`)
|
||||
})
|
||||
mux.HandleFunc("/o/r/releases/tag/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `<span class="Label Label--warning">Pre-release</span>`)
|
||||
})
|
||||
mux.HandleFunc("/o/r/releases/tag/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `<span class="Label Label--success">Latest</span>`)
|
||||
})
|
||||
mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `<a href="/o/r/releases/download/runtime-3731afd-p2/reims-runtime-win-x64-3731afd-p2.tar.zst">a</a>
|
||||
<a href="/o/r/releases/download/runtime-3731afd-p2/reims-runtime-src-3731afd-p2.tar.zst">b</a>
|
||||
<a href="/o/r/releases/download/runtime-3731afd-p2/SHA256SUMS.txt">c</a>`)
|
||||
})
|
||||
mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `<a href="/o/r/releases/download/runtime-3731afd/reims-runtime-win-x64-3731afd.tar.zst">a</a>
|
||||
<a href="/o/r/releases/download/runtime-3731afd/reims-runtime-src-3731afd.tar.zst">b</a>
|
||||
<a href="/o/r/releases/download/runtime-3731afd/SHA256SUMS.txt">c</a>`)
|
||||
})
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/netproxy"
|
||||
)
|
||||
|
||||
// Version is the current Reims-Go release version. Release builds may override
|
||||
@@ -36,7 +38,7 @@ func DefaultSource() Source {
|
||||
return Source{
|
||||
APIBase: DefaultAPIBase,
|
||||
Repo: repo,
|
||||
Client: &http.Client{},
|
||||
Client: netproxy.NewClient(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +145,13 @@ func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, er
|
||||
}
|
||||
req.Header.Set("User-Agent", "reims-go")
|
||||
req.Header.Set("Accept", "application/vnd.github+json")
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user