feat: 完善代理池与抢购链路,发布 0.5.0

This commit is contained in:
yml
2026-11-20 00:48:21 +08:00
parent 2f087ac7f1
commit 98b3dc4b16
28 changed files with 1522 additions and 204 deletions
+100 -27
View File
@@ -26,10 +26,11 @@ import (
type App struct {
ctx context.Context
clientMu sync.RWMutex
client *client.DouyuClient
scheduler *seckill.Scheduler
logStore *logger.MemoryLogStore
clientMu sync.RWMutex
client *client.DouyuClient
schedulerMu sync.RWMutex
scheduler *seckill.Scheduler
logStore *logger.MemoryLogStore
traceMu sync.RWMutex
trace *trace.Recorder
@@ -81,6 +82,18 @@ func (a *App) setClient(c *client.DouyuClient) {
a.clientMu.Unlock()
}
func (a *App) getScheduler() *seckill.Scheduler {
a.schedulerMu.RLock()
defer a.schedulerMu.RUnlock()
return a.scheduler
}
func (a *App) setScheduler(s *seckill.Scheduler) {
a.schedulerMu.Lock()
a.scheduler = s
a.schedulerMu.Unlock()
}
// setCfg 替换配置(写锁保护)。
func (a *App) setCfg(c types.Config) {
a.cfgMu.Lock()
@@ -167,53 +180,113 @@ func (a *App) Startup(ctx context.Context) {
logger.LogEvent("配置", "success", "已迁移旧配置到应用内部目录: %s", a.paths.ConfigFile)
}
// 加载配置并应用运行时设置
a.cfg = config.LoadConfig(a.paths.ConfigFile)
logger.SetMinLevel(a.cfg.LogLevel)
// 优先初始化调度器和账号库,避免前端首屏请求早于启动网络探测时读到 nil。
cfg := config.LoadConfig(a.paths.ConfigFile)
a.setCfg(cfg)
logger.SetMinLevel(cfg.LogLevel)
a.replaceTrace(cfg)
a.replaceTrace(a.cfg)
// 解析当前活动:配置中的 activity ID 决定使用哪套接口参数
act := activity.Get(a.cfg.Activity)
act := activity.Get(cfg.Activity)
if act == nil {
act = activity.Default()
logger.LogEvent("活动", "warn", "配置中的活动 %q 未识别,已回退到默认活动 %s", a.cfg.Activity, act.DisplayName)
logger.LogEvent("活动", "warn", "配置中的活动 %q 未识别,已回退到默认活动 %s", cfg.Activity, act.DisplayName)
}
proxyURL := a.effectiveProxyURL(a.cfg)
a.client, _ = client.NewWithProxy(act, a.cfg.TimeAPIURL, a.getTrace(), proxyURL)
if a.client == nil {
proxyURL := a.effectiveProxyURL(cfg)
initialClient, _ := client.NewWithProxy(act, cfg.TimeAPIURL, a.getTrace(), proxyURL)
if initialClient == nil {
logger.LogEvent("代理", "error", "启动时代理配置无效,已回退直连: %s", client.MaskProxyURL(proxyURL))
a.client, _ = client.NewWithProxy(act, a.cfg.TimeAPIURL, a.getTrace(), "")
initialClient, _ = client.NewWithProxy(act, cfg.TimeAPIURL, a.getTrace(), "")
}
a.setClient(initialClient)
if proxyURL != "" {
logger.LogEvent("代理", "info", "已启用代理: %s", client.MaskProxyURL(proxyURL))
}
a.font = imgpkg.LoadFont(a.paths.FontFiles)
a.scheduler = seckill.New(a.client, a.paths, a.font, a.cfg.Concurrency, a.cfg.Attempts, a.cfg.RetryStages, a.cfg.SeckillMode)
a.scheduler.UpdateProxySettings(a.cfg)
a.scheduler.SetStateChangeCallback(func(state string) {
scheduler := seckill.New(initialClient, a.paths, a.font, cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode)
a.setScheduler(scheduler)
scheduler.UpdateProxySettings(cfg)
scheduler.SetStateChangeCallback(func(state string) {
runtime.EventsEmit(a.ctx, seckillStateEvent, state)
})
a.scheduler.LoadAccounts()
scheduler.LoadAccounts()
startupRefreshTried := false
tryRefreshStartupProxy := func(reason string) bool {
if startupRefreshTried {
return false
}
startupRefreshTried = true
currentCfg := a.getCfg()
refreshedCfg := currentCfg
if err := a.refreshStartupProxy(&refreshedCfg, reason); err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理失败: %v", err)
return false
}
candidate, err := client.NewWithProxy(act, refreshedCfg.TimeAPIURL, a.getTrace(), a.effectiveProxyURL(refreshedCfg))
if err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理地址无效: %v", err)
return false
}
oldClient := a.getClient()
a.setClient(candidate)
a.setCfg(refreshedCfg)
scheduler.UpdateClient(candidate)
scheduler.UpdateProxySettings(refreshedCfg)
if oldClient != nil && oldClient.HTTPClient != nil {
oldClient.HTTPClient.CloseIdleConnections()
}
if oldClient != nil && oldClient.TimeHTTPClient != nil {
oldClient.TimeHTTPClient.CloseIdleConnections()
}
if err := config.SaveConfig(a.paths.ConfigFile, refreshedCfg); err != nil {
logger.LogEvent("代理", "warn", "启动自动刷新代理已生效,但配置保存失败: %v", err)
}
logger.LogEvent("代理", "success", "启动自动刷新代理已生效: %s",
client.MaskProxyURL(a.effectiveProxyURL(refreshedCfg)))
return true
}
if proxyNeedsStartupRefresh(a.getCfg(), time.Now()) {
tryRefreshStartupProxy("当前代理已过期")
}
proxyURL = a.effectiveProxyURL(a.getCfg())
if proxyURL != "" {
if _, err := a.getClient().ProbeServerTime(); err != nil {
logger.LogEvent("代理", "warn", "启动代理探测失败: %v", err)
currentCfg := a.getCfg()
if currentCfg.ProxyEnabled &&
strings.TrimSpace(currentCfg.ProxyAPI) != "" &&
isStartupProxyFailure(err) {
tryRefreshStartupProxy("当前代理连接失败")
}
}
}
startupSample, startupErr := a.getClient().ServerTimeSample()
if err := os.MkdirAll(a.paths.SuccessDir, 0755); err != nil {
logger.LogEvent("图片", "warn", "成功图片目录创建失败,图片保存功能可能不可用: %v", err)
}
if sample, err := a.client.ServerTimeSample(); err == nil {
logger.SetDouyuOffset(sample.Offset)
logger.LogEvent("时间", "success", "服务端时间获取成功: %s", sample.EstimatedServerNow().In(constants.CST).Format("2006-01-02 15:04:05.000"))
if startupErr == nil {
logger.SetDouyuOffset(startupSample.Offset)
logger.LogEvent("时间", "success", "服务端时间获取成功: %s", startupSample.EstimatedServerNow().In(constants.CST).Format("2006-01-02 15:04:05.000"))
} else {
logger.LogEvent("时间", "error", "服务端时间获取失败: %v", err)
logger.LogEvent("时间", "error", "服务端时间获取失败: %v", startupErr)
}
logger.LogEvent("系统", "success", "应用启动完成 | 账号: %d", a.scheduler.AccountCount())
logger.LogEvent("系统", "success", "应用启动完成 | 账号: %d", scheduler.AccountCount())
}
// Shutdown Wails 应用关闭时调用。
func (a *App) Shutdown(ctx context.Context) {
if a.scheduler != nil {
a.scheduler.Close()
if scheduler := a.getScheduler(); scheduler != nil {
scheduler.Close()
}
a.traceMu.Lock()
closeTrace := a.closeTrace
+6
View File
@@ -105,6 +105,12 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
if cfg.AccountsPerProxy > constants.MaxAccountsPerProxy {
cfg.AccountsPerProxy = constants.MaxAccountsPerProxy
}
if cfg.ProxySparePercent <= 0 {
cfg.ProxySparePercent = constants.DefaultProxySparePercent
}
if cfg.ProxySparePercent > constants.MaxProxySparePercent {
cfg.ProxySparePercent = constants.MaxProxySparePercent
}
if cfg.Attempts <= 0 {
cfg.Attempts = constants.DefaultAttempts
}
+12 -4
View File
@@ -29,7 +29,11 @@ func (a *App) loadProducts(refresh bool, accountNames []string) types.ProductPay
options := types.XiaodianProductListOptions{PageSize: cfg.XiaodianPageSize}
var products []types.Product
err := fmt.Errorf("没有可用账号 Cookie")
accounts := productRefreshAccounts(a.scheduler.AccountSnapshot(), accountNames)
scheduler := a.getScheduler()
if scheduler == nil {
return types.ProductPayload{Success: false}
}
accounts := productRefreshAccounts(scheduler.AccountSnapshot(), accountNames)
for _, account := range accounts {
products, err = a.getClient().Products(account.Cookie, options)
if err == nil {
@@ -75,7 +79,11 @@ func productRefreshAccounts(accounts []types.Account, preferredNames []string) [
// GetAccounts 返回账号列表。
func (a *App) GetAccounts() []types.AccountView {
accounts := a.scheduler.AccountSnapshot()
scheduler := a.getScheduler()
if scheduler == nil {
return []types.AccountView{}
}
accounts := scheduler.AccountSnapshot()
list := make([]types.AccountView, 0, len(accounts))
for i, account := range accounts {
list = append(list, types.AccountView{
@@ -100,8 +108,8 @@ func (a *App) setProducts(products []types.Product, fetchedAt time.Time) {
a.products = products
a.productsAt = fetchedAt
a.productsMu.Unlock()
if a.scheduler != nil {
a.scheduler.UpdateProducts(products)
if scheduler := a.getScheduler(); scheduler != nil {
scheduler.UpdateProducts(products)
}
}
+73 -16
View File
@@ -2,6 +2,8 @@ package app
import (
"context"
"fmt"
"strings"
"time"
"douyu_go/internal/client"
@@ -24,27 +26,12 @@ func (a *App) TestProxy(proxyURL string) types.ProxyTestResult {
// FetchProxy 从指定 API 提取一个代理 IP。
func (a *App) FetchProxy(apiURL string) types.ProxyFetchResult {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
service := proxyprovider.NewService()
cfg := a.getCfg()
endpoints, err := service.ExtractWithWhitelist(ctx, apiURL, 1, proxyprovider.WhitelistConfig{
APIURL: apiURL,
LoginPassword: cfg.ProxyWhitelistPassword,
SignKey: cfg.ProxyWhitelistSignKey,
ReplaceOldest: cfg.ProxyWhitelistReplace,
AutoWhitelist: cfg.ProxyAutoWhitelist,
})
endpoints, err := extractProxyEndpoints(cfg, apiURL, 1)
if err != nil {
logger.LogEvent("代理", "warn", "代理提取失败: %v", err)
return types.ProxyFetchResult{Error: err.Error()}
}
if len(endpoints) == 0 {
return types.ProxyFetchResult{
Success: false,
Error: "代理 API 未返回有效地址",
}
}
endpoint := endpoints[0]
expiresAt := int64(0)
if !endpoint.ExpiresAt.IsZero() {
@@ -67,3 +54,73 @@ func (a *App) FetchProxy(apiURL string) types.ProxyFetchResult {
ExpiresAt: expiresAt,
}
}
func extractProxyEndpoints(cfg types.Config, apiURL string, count int) ([]proxyprovider.Endpoint, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
service := proxyprovider.NewService()
endpoints, err := service.ExtractWithWhitelist(ctx, apiURL, count, proxyprovider.WhitelistConfig{
APIURL: apiURL,
LoginPassword: cfg.ProxyWhitelistPassword,
SignKey: cfg.ProxyWhitelistSignKey,
ReplaceOldest: cfg.ProxyWhitelistReplace,
AutoWhitelist: cfg.ProxyAutoWhitelist,
})
if err != nil {
return nil, err
}
if len(endpoints) == 0 {
return nil, fmt.Errorf("代理 API 未返回有效地址")
}
return endpoints, nil
}
func proxyNeedsStartupRefresh(cfg types.Config, now time.Time) bool {
return cfg.ProxyEnabled &&
strings.TrimSpace(cfg.ProxyAPI) != "" &&
cfg.ProxyExpiresAt > 0 &&
now.Add(30*time.Second).UnixMilli() >= cfg.ProxyExpiresAt
}
func isStartupProxyFailure(err error) bool {
if err == nil {
return false
}
message := strings.ToLower(err.Error())
for _, hint := range []string{
"407", "proxy authentication required", "proxyconnect", "connection refused",
"connection reset", "unexpected eof", "context deadline exceeded", "timeout",
"can't assign requested address",
} {
if strings.Contains(message, hint) {
return true
}
}
return false
}
func (a *App) refreshStartupProxy(cfg *types.Config, reason string) error {
if !cfg.ProxyEnabled || strings.TrimSpace(cfg.ProxyAPI) == "" {
return fmt.Errorf("代理提取 API 未配置")
}
endpoints, err := extractProxyEndpoints(*cfg, cfg.ProxyAPI, 1)
if err != nil {
return err
}
endpoint := endpoints[0]
if probe := client.TestProxyConnection(endpoint.URL); !probe.Success {
return fmt.Errorf("新代理连通性校验失败: %s", probe.Error)
}
cfg.ProxyURL = endpoint.URL
cfg.ProxyExpiresAt = 0
if !endpoint.ExpiresAt.IsZero() {
cfg.ProxyExpiresAt = endpoint.ExpiresAt.UnixMilli()
}
expiresLabel := "未知"
if !endpoint.ExpiresAt.IsZero() {
expiresLabel = endpoint.ExpiresAt.In(constants.CST).Format("2006-01-02 15:04:05")
}
logger.LogEvent("代理", "success", "启动时检测到%s,已提取并校验新代理: %s,过期=%s",
reason, client.MaskProxyURL(cfg.ProxyURL), expiresLabel)
return nil
}
+79
View File
@@ -0,0 +1,79 @@
package app
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"douyu_go/internal/types"
)
func TestProxyNeedsStartupRefresh(t *testing.T) {
now := time.Date(2026, 11, 20, 0, 30, 0, 0, time.Local)
base := types.Config{
ProxyEnabled: true,
ProxyAPI: "https://service.ipzan.com/core-extract",
ProxyExpiresAt: now.Add(10 * time.Minute).UnixMilli(),
}
if proxyNeedsStartupRefresh(base, now) {
t.Fatal("未过期代理不应在启动时刷新")
}
base.ProxyExpiresAt = now.Add(20 * time.Second).UnixMilli()
if !proxyNeedsStartupRefresh(base, now) {
t.Fatal("距离过期不足30秒时应提前刷新")
}
base.ProxyEnabled = false
if proxyNeedsStartupRefresh(base, now) {
t.Fatal("代理未启用时不应刷新")
}
}
func TestIsStartupProxyFailure(t *testing.T) {
cases := []struct {
err error
want bool
}{
{err: errors.New(`Get "https://www.douyu.com": Proxy Authentication Required`), want: true},
{err: errors.New("proxyconnect tcp: connection refused"), want: true},
{err: errors.New("Get https://www.douyu.com: unexpected EOF"), want: true},
{err: errors.New("context deadline exceeded"), want: true},
{err: errors.New("业务接口返回库存不足"), want: false},
{err: nil, want: false},
}
for _, tc := range cases {
if got := isStartupProxyFailure(tc.err); got != tc.want {
t.Errorf("isStartupProxyFailure(%v)=%v, want %v", tc.err, got, tc.want)
}
}
}
func TestRefreshStartupProxyValidatesAndUpdatesConfig(t *testing.T) {
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Host == "myip.ipip.net" {
fmt.Fprint(w, "当前 IP:127.0.0.1 来自于:中国 测试")
return
}
http.Error(w, "unexpected request", http.StatusBadGateway)
}))
defer proxyServer.Close()
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, proxyServer.URL)
}))
defer apiServer.Close()
cfg := types.Config{
ProxyEnabled: true,
ProxyAPI: apiServer.URL,
}
app := &App{}
if err := app.refreshStartupProxy(&cfg, "测试"); err != nil {
t.Fatalf("refreshStartupProxy() error = %v", err)
}
if cfg.ProxyURL != proxyServer.URL {
t.Fatalf("ProxyURL=%q, want %q", cfg.ProxyURL, proxyServer.URL)
}
}
+15 -2
View File
@@ -50,7 +50,11 @@ func (a *App) StopSeckill() types.MessageResult {
// GetSeckillStatus 返回当前抢购运行状态。
func (a *App) GetSeckillStatus() types.SimpleResult {
return types.SimpleResult{Success: a.scheduler.IsRunning()}
scheduler := a.getScheduler()
if scheduler == nil {
return types.SimpleResult{Success: false}
}
return types.SimpleResult{Success: scheduler.IsRunning()}
}
// StartFixedSeckill 启动和平小店固定次数/间隔抢购。
@@ -117,7 +121,16 @@ func (a *App) GetLogs(since int64) types.LogsResult {
// GetTime 返回服务端时间和本地时间。
func (a *App) GetTime() types.TimeResult {
serverTime, err := a.getClient().ServerTime()
cli := a.getClient()
if cli == nil {
now := time.Now()
return types.TimeResult{
ServerTime: now.In(constants.CST).Format("2006-01-02 15:04:05.000"),
LocalTime: now.In(constants.CST).Format("2006-01-02 15:04:05.000"),
Source: "localFallback",
}
}
serverTime, err := cli.ServerTime()
source := "currentTime"
if err != nil {
source = "localFallback"
+16
View File
@@ -0,0 +1,16 @@
package app
import "testing"
func TestEarlyFrontendCallsAreSafeBeforeSchedulerReady(t *testing.T) {
app := &App{}
if got := app.GetAccounts(); len(got) != 0 {
t.Fatalf("GetAccounts()=%v, want empty before scheduler init", got)
}
if got := app.GetSeckillStatus(); got.Success {
t.Fatal("GetSeckillStatus() should report not running before scheduler init")
}
if got := app.GetTime(); got.Source != "localFallback" {
t.Fatalf("GetTime().Source=%q, want localFallback", got.Source)
}
}