Files
千川白浪 107a8d73e0 refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 (#200)
* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积

* fix: preserve download recovery and bound PBZX decoding

Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
2026-12-05 20:54:41 +08:00

353 lines
10 KiB
Go

// Package fetch downloads release assets: resumable, and checked against the
// release's SHA256SUMS.txt before the file is handed out. Runtime installs and
// app self-updates share it.
package fetch
import (
"bufio"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/internal/downloader"
)
var (
defaultDownloaderMu sync.RWMutex
defaultDownloaderFn func() downloader.Provider
)
// SetDefaultDownloader installs a provider lookup used by Resume to accelerate
// release asset downloads via the active downloader plugin. Passing nil clears it.
func SetDefaultDownloader(fn func() downloader.Provider) {
defaultDownloaderMu.Lock()
defaultDownloaderFn = fn
defaultDownloaderMu.Unlock()
}
func activeDownloader() downloader.Provider {
defaultDownloaderMu.RLock()
fn := defaultDownloaderFn
defaultDownloaderMu.RUnlock()
if fn == nil {
return nil
}
return fn()
}
// SumsAsset is the checksum file every Reims-Go release carries.
const SumsAsset = "SHA256SUMS.txt"
// Progress reports bytes downloaded so far and the total (0 when unknown).
type Progress func(done, total int64)
// NewRequest builds a GET with a generic client name (nothing about the user;
// GitHub requires a User-Agent) and, for api.github.com only, a token from
// GITHUB_TOKEN or GH_TOKEN.
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
}
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 clientOr(c *http.Client) *http.Client {
if c != nil {
return c
}
return http.DefaultClient
}
// ExpectedSum reads name's hash from the SHA256SUMS.txt at sumsURL
// ("<hex> <name>" lines, as sha256sum writes them).
func ExpectedSum(ctx context.Context, client *http.Client, sumsURL, name string) (string, error) {
if sumsURL == "" {
return "", fmt.Errorf("release has no %s", SumsAsset)
}
req, err := NewRequest(ctx, sumsURL)
if err != nil {
return "", err
}
resp, err := clientOr(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], "*") == name && len(fields[0]) == 64 {
return strings.ToLower(fields[0]), nil
}
}
return "", fmt.Errorf("%s has no entry for %s", SumsAsset, name)
}
// ResumeOptions configures security and streaming safeguards for a resumable download.
type ResumeOptions struct {
// BypassDownloader skips any registered downloader plugin and always uses
// the caller-supplied http.Client (preserving custom CheckRedirect and proxy rules).
BypassDownloader bool
// MaxBytes caps total downloaded bytes on disk (<= 0 disables the cap).
MaxBytes int64
// StallTimeout aborts the download when no bytes arrive for this duration
// (<= 0 disables per-read stall detection).
StallTimeout time.Duration
}
// Resume downloads url to final, continuing a "<final>.part" left by an earlier
// attempt, and keeps the result only when its SHA-256 is want. A final file
// that already matches is returned without downloading. size is the expected
// length (0 when unknown) and only feeds progress.
func Resume(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress) (string, error) {
return resumeWithOptions(ctx, client, url, final, size, want, onProgress, ResumeOptions{})
}
// ResumeDirect behaves like Resume, always using client directly (never
// delegating to activeDownloader plugins) and enforcing opts.MaxBytes and
// opts.StallTimeout.
func ResumeDirect(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
opts.BypassDownloader = true
return resumeWithOptions(ctx, client, url, final, size, want, onProgress, opts)
}
func resumeWithOptions(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
if onProgress == nil {
onProgress = func(int64, int64) {}
}
name := filepath.Base(final)
if st, err := os.Stat(final); err == nil && (opts.MaxBytes <= 0 || st.Size() <= opts.MaxBytes) {
if got, herr := FileSHA256(final); herr == nil && strings.EqualFold(got, want) {
onProgress(size, size)
return final, nil
}
}
part := final + ".part"
// Try the active downloader first unless this transfer requires the
// caller's HTTP client (for example, plugin market downloads).
if !opts.BypassDownloader {
if prov := activeDownloader(); prov != nil {
err := prov.Download(ctx, downloader.Request{
URL: url,
DestPath: part,
ExpectedSize: size,
ExpectedSHA256: want,
Resume: true,
}, func(p downloader.Progress) {
onProgress(p.Done, p.Total)
})
if ctx.Err() != nil {
return "", ctx.Err()
}
if err == nil {
got, hashErr := FileSHA256(part)
switch {
case hashErr != nil:
err = hashErr
case !strings.EqualFold(got, want):
err = fmt.Errorf("SHA256 mismatch (got %s, want %s)", got, want)
default:
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
}
// A parallel partial can contain holes. Discard its checkpoint
// together with the file before the HTTP client starts over.
providerErr := fmt.Errorf("download %s (%s): %w", name, prov.ID(), err)
if err := downloader.DiscardPartial(part); err != nil {
return "", errors.Join(providerErr, err)
}
log.Printf("[fetch] downloader %s failed for %s; retrying with the HTTP client", prov.ID(), name)
path, err := resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
if err != nil {
return "", errors.Join(providerErr, err)
}
return path, nil
}
}
return resumeHTTP(ctx, client, url, final, size, want, onProgress, opts)
}
func resumeHTTP(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) {
name := filepath.Base(final)
part := final + ".part"
if err := downloader.PrepareHTTPResume(part); err != nil {
return "", err
}
for attempt := 0; ; attempt++ {
var have int64
if st, err := os.Stat(part); err == nil {
if opts.MaxBytes > 0 && st.Size() > opts.MaxBytes {
_ = os.Remove(part)
} else {
have = st.Size()
}
}
reqCtx, cancelReq := context.WithCancel(ctx)
req, err := NewRequest(reqCtx, url)
if err != nil {
cancelReq()
return "", err
}
if have > 0 {
req.Header.Set("Range", "bytes="+strconv.FormatInt(have, 10)+"-")
}
resp, err := clientOr(client).Do(req)
if err != nil {
cancelReq()
return "", fmt.Errorf("download %s: %w", name, err)
}
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:
resp.Body.Close()
cancelReq()
os.Remove(part)
if attempt > 0 {
return "", fmt.Errorf("download %s: HTTP 416", name)
}
continue
default:
resp.Body.Close()
cancelReq()
return "", fmt.Errorf("download %s: HTTP %d", name, resp.StatusCode)
}
if opts.MaxBytes > 0 && resp.ContentLength > 0 && have+resp.ContentLength > opts.MaxBytes {
resp.Body.Close()
cancelReq()
_ = os.Remove(part)
return "", fmt.Errorf("download %s: content length %d exceeds %d byte limit", name, have+resp.ContentLength, opts.MaxBytes)
}
total := size
if total <= 0 && resp.ContentLength > 0 {
total = have + resp.ContentLength
}
err = copyBody(resp.Body, cancelReq, part, flags, have, total, opts.MaxBytes, opts.StallTimeout, name, onProgress)
resp.Body.Close()
cancelReq()
if err != nil {
return "", err
}
break
}
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", name, want, got)
}
if err := os.Rename(part, final); err != nil {
return "", err
}
return final, nil
}
func copyBody(body io.Reader, cancelReq context.CancelFunc, part string, flags int, have, total, maxBytes int64, stallTimeout time.Duration, name string, onProgress Progress) error {
f, err := os.OpenFile(part, flags, 0o644)
if err != nil {
return err
}
var (
stalled atomic.Bool
timer *time.Timer
)
if stallTimeout > 0 && cancelReq != nil {
timer = time.AfterFunc(stallTimeout, func() {
stalled.Store(true)
cancelReq()
})
defer timer.Stop()
}
done := have
onProgress(done, total)
buf := make([]byte, 256*1024)
last := time.Now()
for {
n, rerr := body.Read(buf)
if n > 0 {
if timer != nil {
timer.Reset(stallTimeout)
}
if maxBytes > 0 && done+int64(n) > maxBytes {
f.Close()
_ = os.Remove(part)
return fmt.Errorf("download %s: exceeds %d byte limit", name, maxBytes)
}
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()
if stalled.Load() {
return fmt.Errorf("download %s: stalled for %s", name, stallTimeout)
}
return fmt.Errorf("download %s: %w", name, rerr) // .part kept for resume
}
}
if err := f.Close(); err != nil {
return err
}
onProgress(done, total)
return nil
}
// FileSHA256 returns the lowercase hex SHA-256 of the file at path.
func FileSHA256(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}