feat(proxy): 支持品赞分组代理与自动白名单
This commit is contained in:
@@ -116,7 +116,15 @@ type attemptOutcome struct {
|
||||
|
||||
// runAccountAttempt 按活动执行一次完整尝试。
|
||||
func (s *Scheduler) runAccountAttempt(attempt types.ExchangeAttempt, mode types.SeckillMode, ctl *runControl) attemptOutcome {
|
||||
cli := s.clientSnapshot()
|
||||
cli := s.clientForAccount(attempt.Account.Name)
|
||||
if cli == nil {
|
||||
return attemptOutcome{result: types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
Attempt: attempt.Index,
|
||||
Message: "失败|没有可用代理客户端",
|
||||
}}
|
||||
}
|
||||
switch {
|
||||
case cli.Activity.IsXiaodian:
|
||||
// 和平小店正常走 RunXiaodian;这里保留兜底分类,避免万一被路由进来时
|
||||
@@ -136,7 +144,15 @@ func (s *Scheduler) runAccountAttempt(attempt types.ExchangeAttempt, mode types.
|
||||
// 锁单失败立即返回,等待与重试交给外层每账号独立循环,因此单个账号的长退避
|
||||
// 不会阻塞其它账号;锁单成功后的支付阶梯不受 75 秒抢购窗口约束。
|
||||
func (s *Scheduler) runPeaceLockPay(attempt types.ExchangeAttempt, ctl *runControl) attemptOutcome {
|
||||
cli := s.clientSnapshot()
|
||||
cli := s.clientForAccount(attempt.Account.Name)
|
||||
if cli == nil {
|
||||
return attemptOutcome{result: types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
Attempt: attempt.Index,
|
||||
Message: "失败|没有可用代理客户端",
|
||||
}}
|
||||
}
|
||||
out := attemptOutcome{result: types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
@@ -324,7 +340,15 @@ func (s *Scheduler) payOnce(cli *client.DouyuClient, attempt types.ExchangeAttem
|
||||
|
||||
// runDirectExchange 电竞手册直接兑换。
|
||||
func (s *Scheduler) runDirectExchange(attempt types.ExchangeAttempt, reuseCache bool, ctl *runControl) attemptOutcome {
|
||||
cli := s.clientSnapshot()
|
||||
cli := s.clientForAccount(attempt.Account.Name)
|
||||
if cli == nil {
|
||||
return attemptOutcome{result: types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
Attempt: attempt.Index,
|
||||
Message: "失败|没有可用代理客户端",
|
||||
}}
|
||||
}
|
||||
out := attemptOutcome{result: types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
@@ -450,7 +474,7 @@ func (s *Scheduler) rememberAuth(accountName, csrf, roleName string) {
|
||||
|
||||
// runXiaodianAttempt 和平小店专用兑换:跳过手册鉴权、批量限制和预兑换,直接调用 livebuy。
|
||||
func (s *Scheduler) runXiaodianAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
|
||||
cli := s.clientSnapshot()
|
||||
cli := s.clientForAccount(attempt.Account.Name)
|
||||
result := types.ExchangeResult{
|
||||
Account: attempt.Account.Name,
|
||||
Product: attempt.Product.CommodityName,
|
||||
@@ -461,6 +485,10 @@ func (s *Scheduler) runXiaodianAttempt(attempt types.ExchangeAttempt) types.Exch
|
||||
result.Message = "失败|已收到停止指令"
|
||||
return result
|
||||
}
|
||||
if cli == nil {
|
||||
result.Message = "失败|没有可用代理客户端"
|
||||
return result
|
||||
}
|
||||
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name,
|
||||
"和平小店直接兑换: 账号=%s 商品=%s 第%d次",
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
package seckill
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"douyu_go/internal/client"
|
||||
"douyu_go/internal/constants"
|
||||
"douyu_go/internal/logger"
|
||||
proxyprovider "douyu_go/internal/proxy"
|
||||
"douyu_go/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
proxyFetchRounds = 3
|
||||
proxyFetchRetryWait = 300 * time.Millisecond
|
||||
proxyRequestTimeout = 15 * time.Second
|
||||
proxyValidationTimeout = 3 * time.Second
|
||||
proxyValidationWorkers = 3
|
||||
proxyValidateAttempts = 1
|
||||
)
|
||||
|
||||
type proxySettingsSnapshot struct {
|
||||
enabled bool
|
||||
proxyURL string
|
||||
proxyAPI string
|
||||
autoFetchOnTimer bool
|
||||
accountsPerProxy int
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
whitelistSignKey string
|
||||
}
|
||||
|
||||
type validatedProxy struct {
|
||||
url string
|
||||
client *client.DouyuClient
|
||||
rtt time.Duration
|
||||
ip string
|
||||
region string
|
||||
source string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// UpdateProxySettings 运行时更新代理配置。
|
||||
func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
enabled := cfg.ProxyEnabled
|
||||
proxyURL := cfg.ProxyURL
|
||||
proxyAPI := cfg.ProxyAPI
|
||||
autoFetch := cfg.AutoFetchProxyOnSchedule
|
||||
accountsPerProxy := cfg.AccountsPerProxy
|
||||
if accountsPerProxy <= 0 {
|
||||
accountsPerProxy = constants.DefaultAccountsPerProxy
|
||||
}
|
||||
if accountsPerProxy > constants.MaxAccountsPerProxy {
|
||||
accountsPerProxy = constants.MaxAccountsPerProxy
|
||||
}
|
||||
proxyURL = strings.TrimSpace(proxyURL)
|
||||
proxyAPI = strings.TrimSpace(proxyAPI)
|
||||
whitelistPassword := strings.TrimSpace(cfg.ProxyWhitelistPassword)
|
||||
whitelistSignKey := strings.TrimSpace(cfg.ProxyWhitelistSignKey)
|
||||
s.proxyMu.Lock()
|
||||
changed := s.proxyEnabled != enabled ||
|
||||
s.proxyURL != proxyURL ||
|
||||
s.proxyAPI != proxyAPI ||
|
||||
s.autoFetchProxyOnSchedule != autoFetch ||
|
||||
s.accountsPerProxy != accountsPerProxy ||
|
||||
s.autoWhitelist != cfg.ProxyAutoWhitelist ||
|
||||
s.whitelistReplace != cfg.ProxyWhitelistReplace ||
|
||||
s.whitelistPassword != whitelistPassword ||
|
||||
s.whitelistSignKey != whitelistSignKey
|
||||
s.proxyEnabled = enabled
|
||||
s.proxyURL = proxyURL
|
||||
s.proxyAPI = proxyAPI
|
||||
s.autoFetchProxyOnSchedule = autoFetch
|
||||
s.accountsPerProxy = accountsPerProxy
|
||||
s.autoWhitelist = cfg.ProxyAutoWhitelist
|
||||
s.whitelistReplace = cfg.ProxyWhitelistReplace
|
||||
s.whitelistPassword = whitelistPassword
|
||||
s.whitelistSignKey = whitelistSignKey
|
||||
s.proxyMu.Unlock()
|
||||
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
s.clientMu.Lock()
|
||||
s.accountClientsDirty = true
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) proxySettings() proxySettingsSnapshot {
|
||||
s.proxyMu.RLock()
|
||||
defer s.proxyMu.RUnlock()
|
||||
size := s.accountsPerProxy
|
||||
if size <= 0 {
|
||||
size = constants.DefaultAccountsPerProxy
|
||||
}
|
||||
if size > constants.MaxAccountsPerProxy {
|
||||
size = constants.MaxAccountsPerProxy
|
||||
}
|
||||
return proxySettingsSnapshot{
|
||||
enabled: s.proxyEnabled,
|
||||
proxyURL: s.proxyURL,
|
||||
proxyAPI: s.proxyAPI,
|
||||
autoFetchOnTimer: s.autoFetchProxyOnSchedule,
|
||||
accountsPerProxy: size,
|
||||
autoWhitelist: s.autoWhitelist,
|
||||
whitelistReplace: s.whitelistReplace,
|
||||
whitelistPassword: s.whitelistPassword,
|
||||
whitelistSignKey: s.whitelistSignKey,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) closeAccountClients() {
|
||||
s.clientMu.Lock()
|
||||
old := s.accountClients
|
||||
s.accountClients = make(map[string]*client.DouyuClient)
|
||||
s.accountClientOrder = nil
|
||||
s.accountClientsDirty = true
|
||||
s.accountClientsExpireAt = time.Time{}
|
||||
s.clientMu.Unlock()
|
||||
closeDouyuClients(old)
|
||||
}
|
||||
|
||||
func (s *Scheduler) replaceAccountClients(accountClients map[string]*client.DouyuClient, order []*client.DouyuClient, expiresAt time.Time) {
|
||||
s.clientMu.Lock()
|
||||
old := s.accountClients
|
||||
s.accountClients = accountClients
|
||||
s.accountClientOrder = order
|
||||
s.accountClientsDirty = false
|
||||
s.accountClientsExpireAt = expiresAt
|
||||
s.clientMu.Unlock()
|
||||
closeDouyuClients(old)
|
||||
}
|
||||
|
||||
func closeDouyuClients(clients map[string]*client.DouyuClient) {
|
||||
seen := make(map[*client.DouyuClient]struct{}, len(clients))
|
||||
for _, cli := range clients {
|
||||
if cli == nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[cli]; ok {
|
||||
continue
|
||||
}
|
||||
seen[cli] = struct{}{}
|
||||
if cli.HTTPClient != nil {
|
||||
cli.HTTPClient.CloseIdleConnections()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) accountClientsCover(accountNames []string) bool {
|
||||
if len(accountNames) == 0 {
|
||||
return true
|
||||
}
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
if len(s.accountClients) == 0 {
|
||||
return false
|
||||
}
|
||||
if s.accountClientsDirty {
|
||||
return false
|
||||
}
|
||||
if !s.accountClientsExpireAt.IsZero() && !time.Now().Before(s.accountClientsExpireAt.Add(-30*time.Second)) {
|
||||
return false
|
||||
}
|
||||
for _, name := range accountNames {
|
||||
if s.accountClients[name] == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Scheduler) calibrationClient() *client.DouyuClient {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
if len(s.accountClientOrder) > 0 && s.accountClientOrder[0] != nil {
|
||||
return s.accountClientOrder[0]
|
||||
}
|
||||
return s.client
|
||||
}
|
||||
|
||||
func (s *Scheduler) allClients() []*client.DouyuClient {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
out := make([]*client.DouyuClient, 0, len(s.accountClientOrder)+1)
|
||||
seen := make(map[*client.DouyuClient]struct{}, len(s.accountClientOrder)+1)
|
||||
if s.client != nil {
|
||||
seen[s.client] = struct{}{}
|
||||
out = append(out, s.client)
|
||||
}
|
||||
for _, cli := range s.accountClientOrder {
|
||||
if cli == nil {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[cli]; ok {
|
||||
continue
|
||||
}
|
||||
seen[cli] = struct{}{}
|
||||
out = append(out, cli)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// prepareProxyGroups 将本次参与抢购的账号按固定顺序分组,并为每组准备独立客户端。
|
||||
// forceRefresh=true 用于定时任务启动前主动刷新短效代理。
|
||||
func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceRefresh bool) error {
|
||||
cfg := s.proxySettings()
|
||||
names := selectedAccountNames(accountProducts)
|
||||
if len(names) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !cfg.enabled {
|
||||
s.closeAccountClients()
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.accountClientsCover(names) {
|
||||
return nil
|
||||
}
|
||||
|
||||
groups := chunkAccountNames(names, cfg.accountsPerProxy)
|
||||
base := s.clientSnapshot()
|
||||
if base == nil {
|
||||
return errors.New("基础客户端未初始化")
|
||||
}
|
||||
|
||||
poolStartedAt := time.Now()
|
||||
proxies, err := s.buildProxyPool(base, cfg, len(groups))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(proxies) < len(groups) {
|
||||
return fmt.Errorf("代理数量不足: 需要%d组,实际%d组", len(groups), len(proxies))
|
||||
}
|
||||
|
||||
accountClients := make(map[string]*client.DouyuClient, len(names))
|
||||
clientOrder := make([]*client.DouyuClient, 0, len(groups))
|
||||
for i, group := range groups {
|
||||
proxy := proxies[i]
|
||||
clientOrder = append(clientOrder, proxy.client)
|
||||
for _, name := range group {
|
||||
accountClients[name] = proxy.client
|
||||
}
|
||||
logger.LogEvent("代理", "success", "代理组%d: 账号=%d 出口=%s IP=%s 归属=%s RTT=%s 来源=%s",
|
||||
i+1, len(group), client.MaskProxyURL(proxy.url), proxy.ip, proxy.region,
|
||||
proxy.rtt.Round(time.Millisecond), proxy.source)
|
||||
}
|
||||
expiresAt := time.Time{}
|
||||
if cfg.proxyAPI != "" {
|
||||
expiresAt = proxyPoolExpiresAt(cfg.proxyAPI, poolStartedAt)
|
||||
}
|
||||
for _, proxy := range proxies {
|
||||
if proxy.expiresAt.IsZero() {
|
||||
continue
|
||||
}
|
||||
if expiresAt.IsZero() || proxy.expiresAt.Before(expiresAt) {
|
||||
expiresAt = proxy.expiresAt
|
||||
}
|
||||
}
|
||||
s.replaceAccountClients(accountClients, clientOrder, expiresAt)
|
||||
logger.LogEvent("代理", "success", "代理分组完成: 账号=%d,每组=%d,代理组=%d",
|
||||
len(names), cfg.accountsPerProxy, len(groups))
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrepareProxyGroups 供立即抢购入口在启动前同步准备代理,便于把错误直接返回给界面。
|
||||
func (s *Scheduler) PrepareProxyGroups(accountProducts map[string]string) error {
|
||||
return s.prepareProxyGroups(accountProducts, false)
|
||||
}
|
||||
|
||||
func selectedAccountNames(accountProducts map[string]string) []string {
|
||||
names := make([]string, 0, len(accountProducts))
|
||||
for name, productID := range accountProducts {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" || strings.TrimSpace(productID) == "" {
|
||||
continue
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
func chunkAccountNames(names []string, size int) [][]string {
|
||||
if size <= 0 {
|
||||
size = constants.DefaultAccountsPerProxy
|
||||
}
|
||||
if size > constants.MaxAccountsPerProxy {
|
||||
size = constants.MaxAccountsPerProxy
|
||||
}
|
||||
groups := make([][]string, 0, (len(names)+size-1)/size)
|
||||
for start := 0; start < len(names); start += size {
|
||||
end := start + size
|
||||
if end > len(names) {
|
||||
end = len(names)
|
||||
}
|
||||
groups = append(groups, append([]string(nil), names[start:end]...))
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
func (s *Scheduler) buildProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int) ([]validatedProxy, error) {
|
||||
if count <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if cfg.proxyAPI != "" {
|
||||
proxies, err := s.fetchAndValidateProxyPool(base, cfg, count)
|
||||
if err == nil && len(proxies) >= count {
|
||||
return proxies, nil
|
||||
}
|
||||
if err != nil {
|
||||
logger.LogEvent("代理", "warn", "动态代理提取未完全成功: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
staticURLs := splitProxyURLs(cfg.proxyURL)
|
||||
if len(staticURLs) == 0 {
|
||||
return nil, errors.New("代理已启用,但没有可用的提取 API 或静态代理")
|
||||
}
|
||||
if len(staticURLs) == 1 {
|
||||
logger.LogEvent("代理", "warn", "当前只有一个静态代理,%d 个账号组将共享该出口", count)
|
||||
}
|
||||
proxies := make([]validatedProxy, 0, count)
|
||||
for i := 0; i < count; i++ {
|
||||
rawURL := staticURLs[i%len(staticURLs)]
|
||||
proxy, err := s.validateProxy(base, rawURL, "静态")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("静态代理组%d不可用: %w", i+1, err)
|
||||
}
|
||||
proxies = append(proxies, proxy)
|
||||
}
|
||||
return proxies, nil
|
||||
}
|
||||
|
||||
func splitProxyURLs(raw string) []string {
|
||||
parts := strings.FieldsFunc(raw, func(r rune) bool {
|
||||
return r == '\n' || r == '\r' || r == ';' || r == ','
|
||||
})
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
part = strings.TrimSpace(part)
|
||||
if part != "" {
|
||||
out = append(out, part)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Scheduler) fetchAndValidateProxyPool(base *client.DouyuClient, cfg proxySettingsSnapshot, count int) ([]validatedProxy, error) {
|
||||
service := s.proxyService
|
||||
if service == nil {
|
||||
service = proxyprovider.NewService()
|
||||
s.proxyService = service
|
||||
}
|
||||
|
||||
proxies := make([]validatedProxy, 0, count)
|
||||
seen := make(map[string]struct{}, count)
|
||||
var lastErr error
|
||||
|
||||
for round := 0; round < proxyFetchRounds; round++ {
|
||||
need := count - len(proxies)
|
||||
if need <= 0 {
|
||||
break
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), proxyRequestTimeout)
|
||||
endpoints, err := service.ExtractWithWhitelist(ctx, cfg.proxyAPI, need, proxyprovider.WhitelistConfig{
|
||||
APIURL: cfg.proxyAPI,
|
||||
LoginPassword: cfg.whitelistPassword,
|
||||
SignKey: cfg.whitelistSignKey,
|
||||
ReplaceOldest: cfg.whitelistReplace,
|
||||
AutoWhitelist: cfg.autoWhitelist,
|
||||
})
|
||||
cancel()
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if proxyprovider.IsFatal(err) {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
validated := s.validateProxyBatch(base, endpoints)
|
||||
for _, item := range validated {
|
||||
if item.err != nil {
|
||||
lastErr = item.err
|
||||
continue
|
||||
}
|
||||
if !item.endpoint.ExpiresAt.IsZero() && !time.Now().Before(item.endpoint.ExpiresAt) {
|
||||
lastErr = fmt.Errorf("代理 %s 已过期", item.endpoint.IP)
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[item.endpoint.URL]; exists {
|
||||
continue
|
||||
}
|
||||
seen[item.endpoint.URL] = struct{}{}
|
||||
proxy := item.proxy
|
||||
if proxy.ip == "" {
|
||||
proxy.ip = item.endpoint.IP
|
||||
}
|
||||
if proxy.region == "" {
|
||||
proxy.region = item.endpoint.Region
|
||||
}
|
||||
proxy.expiresAt = item.endpoint.ExpiresAt
|
||||
proxies = append(proxies, proxy)
|
||||
}
|
||||
}
|
||||
|
||||
if round < proxyFetchRounds-1 {
|
||||
time.Sleep(proxyFetchRetryWait)
|
||||
}
|
||||
}
|
||||
|
||||
if len(proxies) < count {
|
||||
if lastErr != nil {
|
||||
return proxies, lastErr
|
||||
}
|
||||
return proxies, fmt.Errorf("代理 API 仅返回 %d/%d 个有效代理", len(proxies), count)
|
||||
}
|
||||
return proxies, nil
|
||||
}
|
||||
|
||||
func proxyPoolExpiresAt(apiURL string, now time.Time) time.Time {
|
||||
minutes := 10
|
||||
if u, err := url.Parse(strings.TrimSpace(apiURL)); err == nil {
|
||||
query := u.Query()
|
||||
raw := query.Get("minute")
|
||||
if raw == "" {
|
||||
raw = query.Get("min")
|
||||
}
|
||||
if value, err := strconv.Atoi(raw); err == nil && value > 0 && value <= 60 {
|
||||
minutes = value
|
||||
}
|
||||
}
|
||||
return now.Add(time.Duration(minutes) * time.Minute)
|
||||
}
|
||||
|
||||
func (s *Scheduler) validateProxy(base *client.DouyuClient, proxyURL, source string) (validatedProxy, error) {
|
||||
cli, err := client.NewWithProxy(base.Activity, base.TimeAPIURL, base.Trace, proxyURL)
|
||||
if err != nil {
|
||||
return validatedProxy{}, err
|
||||
}
|
||||
if cli.HTTPClient != nil && cli.HTTPClient.Timeout > proxyValidationTimeout {
|
||||
cli.HTTPClient.Timeout = proxyValidationTimeout
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < proxyValidateAttempts; attempt++ {
|
||||
sample, sampleErr := cli.ServerTimeSample()
|
||||
if sampleErr == nil && !sample.Fallback {
|
||||
return validatedProxy{
|
||||
url: proxyURL,
|
||||
client: cli,
|
||||
rtt: sample.RTT,
|
||||
source: source,
|
||||
}, nil
|
||||
}
|
||||
if sampleErr != nil {
|
||||
lastErr = sampleErr
|
||||
} else {
|
||||
lastErr = errors.New("斗鱼时间接口测试失败")
|
||||
}
|
||||
}
|
||||
if cli.HTTPClient != nil {
|
||||
cli.HTTPClient.CloseIdleConnections()
|
||||
}
|
||||
return validatedProxy{}, lastErr
|
||||
}
|
||||
|
||||
type proxyValidationResult struct {
|
||||
endpoint proxyprovider.Endpoint
|
||||
proxy validatedProxy
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *Scheduler) validateProxyBatch(base *client.DouyuClient, endpoints []proxyprovider.Endpoint) []proxyValidationResult {
|
||||
if len(endpoints) == 0 {
|
||||
return nil
|
||||
}
|
||||
workers := proxyValidationWorkers
|
||||
if len(endpoints) < workers {
|
||||
workers = len(endpoints)
|
||||
}
|
||||
jobs := make(chan proxyprovider.Endpoint)
|
||||
results := make(chan proxyValidationResult, len(endpoints))
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for endpoint := range jobs {
|
||||
proxy, err := s.validateProxy(base, endpoint.URL, "API/"+endpoint.Provider)
|
||||
results <- proxyValidationResult{endpoint: endpoint, proxy: proxy, err: err}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for _, endpoint := range endpoints {
|
||||
jobs <- endpoint
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
out := make([]proxyValidationResult, 0, len(endpoints))
|
||||
for result := range results {
|
||||
out = append(out, result)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func accountProductsForTasks(tasks []types.ExchangeAttempt) map[string]string {
|
||||
out := make(map[string]string, len(tasks))
|
||||
for _, task := range tasks {
|
||||
out[task.Account.Name] = task.Product.CommodityID
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package seckill
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"douyu_go/internal/activity"
|
||||
"douyu_go/internal/client"
|
||||
"douyu_go/internal/trace"
|
||||
"douyu_go/internal/types"
|
||||
)
|
||||
|
||||
func TestChunkAccountNames(t *testing.T) {
|
||||
names := []string{"k", "a", "i", "c", "b", "h", "e", "d", "g", "f", "j"}
|
||||
groups := chunkAccountNames(names, 5)
|
||||
if len(groups) != 3 {
|
||||
t.Fatalf("groups=%d, want 3", len(groups))
|
||||
}
|
||||
if len(groups[0]) != 5 || len(groups[1]) != 5 || len(groups[2]) != 1 {
|
||||
t.Fatalf("unexpected group sizes: %d,%d,%d", len(groups[0]), len(groups[1]), len(groups[2]))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitProxyURLs(t *testing.T) {
|
||||
got := splitProxyURLs("http://a:1\nhttp://b:2; http://c:3,http://d:4")
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("splitProxyURLs()=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolExpiresAtUsesMinuteParameter(t *testing.T) {
|
||||
now := time.Date(2026, 11, 19, 12, 0, 0, 0, time.Local)
|
||||
got := proxyPoolExpiresAt("https://example.test/extract?minute=10", now)
|
||||
if want := now.Add(10 * time.Minute); !got.Equal(want) {
|
||||
t.Fatalf("expiresAt=%s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountClientsRespectExpiryAndSettingsRevision(t *testing.T) {
|
||||
scheduler := &Scheduler{
|
||||
client: &client.DouyuClient{},
|
||||
accountClients: make(map[string]*client.DouyuClient),
|
||||
}
|
||||
groupClient := &client.DouyuClient{}
|
||||
scheduler.replaceAccountClients(
|
||||
map[string]*client.DouyuClient{"a": groupClient},
|
||||
[]*client.DouyuClient{groupClient},
|
||||
time.Now().Add(time.Minute),
|
||||
)
|
||||
if !scheduler.accountClientsCover([]string{"a"}) {
|
||||
t.Fatal("未过期代理组应可复用")
|
||||
}
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
AutoFetchProxyOnSchedule: true,
|
||||
AccountsPerProxy: 5,
|
||||
})
|
||||
if scheduler.accountClientsCover([]string{"a"}) {
|
||||
t.Fatal("配置变更后代理组应标记为需要刷新")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
timeAPIURL := "http://douyu.test/time"
|
||||
proxyServers := make([]*httptest.Server, 0, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
proxyServers = append(proxyServers, newTimeProxyServer(t))
|
||||
}
|
||||
var next int32
|
||||
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
index := int(atomic.AddInt32(&next, 1)-1) % len(proxyServers)
|
||||
fmt.Fprint(w, proxyServers[index].URL)
|
||||
}))
|
||||
defer apiServer.Close()
|
||||
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, timeAPIURL, &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
AutoFetchProxyOnSchedule: true,
|
||||
AccountsPerProxy: 2,
|
||||
})
|
||||
|
||||
accountProducts := make(map[string]string)
|
||||
for _, name := range []string{"a", "b", "c", "d", "e"} {
|
||||
accountProducts[name] = "goods-1"
|
||||
}
|
||||
if err := scheduler.prepareProxyGroups(accountProducts, true); err != nil {
|
||||
t.Fatalf("prepareProxyGroups() error = %v", err)
|
||||
}
|
||||
|
||||
if scheduler.clientForAccount("a") != scheduler.clientForAccount("b") {
|
||||
t.Fatal("a 和 b 应使用同一个代理客户端")
|
||||
}
|
||||
if scheduler.clientForAccount("b") == scheduler.clientForAccount("c") {
|
||||
t.Fatal("b 和 c 不应使用同一个代理客户端")
|
||||
}
|
||||
if scheduler.clientForAccount("c") != scheduler.clientForAccount("d") {
|
||||
t.Fatal("c 和 d 应使用同一个代理客户端")
|
||||
}
|
||||
if scheduler.clientForAccount("e") == scheduler.clientForAccount("a") {
|
||||
t.Fatal("e 应使用独立代理客户端")
|
||||
}
|
||||
}
|
||||
|
||||
func newTimeProxyServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
now := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"error":0,"data":{"preExchange":{"currentTime":%q}}}`, now)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"douyu_go/internal/client"
|
||||
"douyu_go/internal/constants"
|
||||
"douyu_go/internal/logger"
|
||||
"douyu_go/internal/types"
|
||||
@@ -47,12 +46,9 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
|
||||
s.scheduleTimers(ap, targetTime, triggerTime, calibration, req.Attempts, req.DelayMs, false)
|
||||
|
||||
s.proxyMu.RLock()
|
||||
autoFetch := s.autoFetchProxyOnSchedule
|
||||
apiURL := s.proxyAPI
|
||||
s.proxyMu.RUnlock()
|
||||
proxyCfg := s.proxySettings()
|
||||
|
||||
if autoFetch && apiURL != "" {
|
||||
if proxyCfg.enabled && proxyCfg.autoFetchOnTimer && proxyCfg.proxyAPI != "" {
|
||||
proxyFetchRemain := triggerTime.Sub(serverTime) - proxyFetchBeforeTrigger
|
||||
if proxyFetchRemain < 0 {
|
||||
proxyFetchRemain = 0
|
||||
@@ -62,20 +58,11 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
if s.IsRunning() {
|
||||
return
|
||||
}
|
||||
logger.LogEvent("代理", "info", "定时任务触发前,自动从 API 提取最新独立代理...")
|
||||
res, err := client.FetchProxyFromAPI(apiURL)
|
||||
if err != nil {
|
||||
logger.LogEvent("代理", "warn", "定时自动提取代理失败: %v,继续使用现有网络通道", err)
|
||||
logger.LogEvent("代理", "info", "定时任务触发前,自动提取并校验分组代理...")
|
||||
if err := s.prepareProxyGroups(ap, true); err != nil {
|
||||
logger.LogEvent("代理", "error", "定时分组代理准备失败: %v", err)
|
||||
return
|
||||
}
|
||||
cli := s.clientSnapshot()
|
||||
if cli != nil {
|
||||
if err := cli.SetProxy(res.ProxyURL); err != nil {
|
||||
logger.LogEvent("代理", "warn", "应用提取代理失败: %v", err)
|
||||
} else {
|
||||
logger.LogEvent("代理", "success", "定时自动应用最新代理: %s (IP=%s 归属=%s)", res.ProxyURL, res.IP, res.Region)
|
||||
}
|
||||
}
|
||||
})
|
||||
s.scheduleMu.Unlock()
|
||||
}
|
||||
@@ -202,7 +189,10 @@ func (s *Scheduler) CancelSchedule() bool {
|
||||
}
|
||||
|
||||
func (s *Scheduler) calibrateDouyuTime(label string) types.TimeCalibration {
|
||||
cli := s.clientSnapshot()
|
||||
cli := s.calibrationClient()
|
||||
if cli == nil {
|
||||
return types.TimeCalibration{Fallback: true}
|
||||
}
|
||||
calibration, err := cli.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
|
||||
if err != nil {
|
||||
logger.LogEvent("时间", "warn", "%s校准降级: %v", label, err)
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"douyu_go/internal/constants"
|
||||
"douyu_go/internal/image"
|
||||
"douyu_go/internal/logger"
|
||||
proxyprovider "douyu_go/internal/proxy"
|
||||
"douyu_go/internal/types"
|
||||
"douyu_go/internal/utils"
|
||||
)
|
||||
@@ -27,7 +28,7 @@ const (
|
||||
timeCalibrateRounds = 3
|
||||
timeCalibrateWait = 1200 * time.Millisecond
|
||||
resyncBeforeTrigger = 8 * time.Second
|
||||
proxyFetchBeforeTrigger = 15 * time.Second
|
||||
proxyFetchBeforeTrigger = 30 * time.Second
|
||||
calibrationHistorySize = 3
|
||||
maxCooldownCount = 5
|
||||
xiaodianDefaultDelay = 500 * time.Millisecond
|
||||
@@ -59,8 +60,13 @@ type runSettings struct {
|
||||
type Scheduler struct {
|
||||
clientMu sync.RWMutex
|
||||
client *client.DouyuClient
|
||||
paths types.AppPaths
|
||||
font *truetype.Font
|
||||
// accountClients 按账号名路由到独立的代理客户端;未命中的账号使用 client。
|
||||
accountClients map[string]*client.DouyuClient
|
||||
accountClientOrder []*client.DouyuClient
|
||||
accountClientsDirty bool
|
||||
accountClientsExpireAt time.Time
|
||||
paths types.AppPaths
|
||||
font *truetype.Font
|
||||
|
||||
successImages *image.SuccessImageSaver
|
||||
|
||||
@@ -90,18 +96,24 @@ type Scheduler struct {
|
||||
// pendingClient 保存运行中收到的客户端更新,当前任务结束后自动应用。
|
||||
pendingClient *client.DouyuClient
|
||||
|
||||
scheduleMu sync.Mutex
|
||||
schedule *time.Timer
|
||||
warmupSchedule *time.Timer
|
||||
resyncSchedule *time.Timer
|
||||
proxyFetchSchedule *time.Timer
|
||||
warmupGen int64
|
||||
scheduleMu sync.Mutex
|
||||
schedule *time.Timer
|
||||
warmupSchedule *time.Timer
|
||||
resyncSchedule *time.Timer
|
||||
proxyFetchSchedule *time.Timer
|
||||
warmupGen int64
|
||||
|
||||
proxyMu sync.RWMutex
|
||||
proxyEnabled bool
|
||||
proxyURL string
|
||||
proxyAPI string
|
||||
autoFetchProxyOnSchedule bool
|
||||
accountsPerProxy int
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
whitelistSignKey string
|
||||
proxyService *proxyprovider.Service
|
||||
|
||||
warmupsMu sync.RWMutex
|
||||
warmups map[string]types.WarmupData
|
||||
@@ -143,6 +155,7 @@ func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, con
|
||||
}
|
||||
scheduler := &Scheduler{
|
||||
client: cli,
|
||||
accountClients: make(map[string]*client.DouyuClient),
|
||||
paths: paths,
|
||||
font: font,
|
||||
accounts: NewAccountStore(paths.AccountFile, paths.LegacyAccountFile),
|
||||
@@ -161,6 +174,8 @@ func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, con
|
||||
attemptCache: make(map[string]*types.AttemptCache),
|
||||
products: make(map[string]types.Product),
|
||||
calibrationOffsets: make([]time.Duration, 0, calibrationHistorySize),
|
||||
accountsPerProxy: constants.DefaultAccountsPerProxy,
|
||||
proxyService: proxyprovider.NewService(),
|
||||
}
|
||||
scheduler.scoreBaselines.Load()
|
||||
scheduler.loadLatestXiaodianReport()
|
||||
@@ -169,6 +184,7 @@ func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, con
|
||||
|
||||
// Close 关闭调度器的后台资源。
|
||||
func (s *Scheduler) Close() {
|
||||
s.closeAccountClients()
|
||||
if s.successImages != nil {
|
||||
s.successImages.Close()
|
||||
}
|
||||
@@ -185,6 +201,16 @@ func (s *Scheduler) clientSnapshot() *client.DouyuClient {
|
||||
return s.client
|
||||
}
|
||||
|
||||
// clientForAccount 返回账号所属代理组的客户端,未分组时回退到基础客户端。
|
||||
func (s *Scheduler) clientForAccount(accountName string) *client.DouyuClient {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
if cli := s.accountClients[accountName]; cli != nil {
|
||||
return cli
|
||||
}
|
||||
return s.client
|
||||
}
|
||||
|
||||
// UpdateClient 热替换底层 HTTP 客户端(用于活动切换)。
|
||||
// 若有抢购任务正在运行则暂存新客户端,当前任务结束后自动应用,并返回 false。
|
||||
func (s *Scheduler) UpdateClient(newClient *client.DouyuClient) bool {
|
||||
@@ -205,12 +231,18 @@ func (s *Scheduler) UpdateClient(newClient *client.DouyuClient) bool {
|
||||
|
||||
func (s *Scheduler) replaceClient(newClient *client.DouyuClient) {
|
||||
s.clientMu.Lock()
|
||||
defer s.clientMu.Unlock()
|
||||
old := s.client
|
||||
oldGroups := s.accountClients
|
||||
s.client = newClient
|
||||
s.accountClients = make(map[string]*client.DouyuClient)
|
||||
s.accountClientOrder = nil
|
||||
s.accountClientsDirty = true
|
||||
s.accountClientsExpireAt = time.Time{}
|
||||
s.clientMu.Unlock()
|
||||
if old != nil && old.HTTPClient != nil {
|
||||
old.HTTPClient.CloseIdleConnections()
|
||||
}
|
||||
closeDouyuClients(oldGroups)
|
||||
}
|
||||
|
||||
// UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。
|
||||
@@ -246,16 +278,6 @@ func (s *Scheduler) UpdateSettings(concurrency, attempts int, retryStages []type
|
||||
s.seckillMode = normalizeSeckillMode(seckillMode)
|
||||
}
|
||||
|
||||
// UpdateProxySettings 运行时更新代理配置。
|
||||
func (s *Scheduler) UpdateProxySettings(enabled bool, proxyURL, proxyAPI string, autoFetch bool) {
|
||||
s.proxyMu.Lock()
|
||||
defer s.proxyMu.Unlock()
|
||||
s.proxyEnabled = enabled
|
||||
s.proxyURL = proxyURL
|
||||
s.proxyAPI = proxyAPI
|
||||
s.autoFetchProxyOnSchedule = autoFetch
|
||||
}
|
||||
|
||||
func (s *Scheduler) settingsSnapshot() runSettings {
|
||||
s.settingsMu.RLock()
|
||||
settings := runSettings{
|
||||
@@ -449,6 +471,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
logger.LogEvent("抢购", "warn", "没有可执行的抢购任务")
|
||||
return
|
||||
}
|
||||
if err := s.prepareProxyGroups(accountProductsForTasks(tasks), false); err != nil {
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
deadline := start.Add(seckillMaxDuration)
|
||||
@@ -467,7 +493,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
|
||||
// 逐条网络日志已降为 debug 级,这里开始统计每类接口的调用情况,
|
||||
// 任务结束时输出一行聚合结果。
|
||||
if cli := s.clientSnapshot(); cli != nil {
|
||||
for _, cli := range s.allClients() {
|
||||
if cli == nil {
|
||||
continue
|
||||
}
|
||||
cli.ResetRequestStats()
|
||||
}
|
||||
|
||||
@@ -484,8 +513,8 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
|
||||
s.logRunSummary(outcomes, ctl, time.Since(start))
|
||||
// 先核对积分(会产生"积分余额"请求,一并计入后面的接口统计)。
|
||||
s.verifyRunResults(outcomes, ctl, s.clientSnapshot())
|
||||
s.logNetworkSummary(s.clientSnapshot())
|
||||
s.verifyRunResults(outcomes, ctl)
|
||||
s.logNetworkSummary()
|
||||
}
|
||||
|
||||
// verifyRunResults 抢购结束后对成功账号核对积分余额。
|
||||
@@ -494,8 +523,9 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
// 2026-09-30 就出现过订单实际已支付、程序却报成失败的情况,只看接口返回不够。
|
||||
// 核对在任务结束之后进行,不影响抢购本身;单个账号查询失败只记警告,
|
||||
// 不改变"抢到"这个结论。
|
||||
func (s *Scheduler) verifyRunResults(outcomes []accountOutcome, ctl *runControl, cli *client.DouyuClient) {
|
||||
if cli == nil || cli.Activity.ScoreURL == "" {
|
||||
func (s *Scheduler) verifyRunResults(outcomes []accountOutcome, ctl *runControl) {
|
||||
base := s.clientSnapshot()
|
||||
if base == nil || base.Activity.ScoreURL == "" {
|
||||
return
|
||||
}
|
||||
successes := make([]accountOutcome, 0, len(outcomes))
|
||||
@@ -521,6 +551,11 @@ func (s *Scheduler) verifyRunResults(outcomes []accountOutcome, ctl *runControl,
|
||||
logger.LogAccountEvent("核对", "warn", out.account, "积分核对跳过: 账号=%s 没有可用 Cookie", out.account)
|
||||
return
|
||||
}
|
||||
cli := s.clientForAccount(out.account)
|
||||
if cli == nil {
|
||||
logger.LogAccountEvent("核对", "warn", out.account, "积分核对跳过: 账号=%s 没有可用客户端", out.account)
|
||||
return
|
||||
}
|
||||
if ctl != nil {
|
||||
if !ctl.enter() {
|
||||
return
|
||||
@@ -604,8 +639,8 @@ func (s *Scheduler) ForgetScoreBaselines(accountNames []string) {
|
||||
// 只在"添加账号"这类抢购之外的操作里调用:账号多的时候,
|
||||
// 抢购链路(预热或触发时刻)绝不能承担这批额外请求。
|
||||
func (s *Scheduler) FetchScoreBaselines(accounts []types.Account) {
|
||||
cli := s.clientSnapshot()
|
||||
if cli == nil || cli.Activity.ScoreURL == "" || len(accounts) == 0 {
|
||||
base := s.clientSnapshot()
|
||||
if base == nil || base.Activity.ScoreURL == "" || len(accounts) == 0 {
|
||||
return
|
||||
}
|
||||
if s.IsRunning() {
|
||||
@@ -628,6 +663,11 @@ func (s *Scheduler) FetchScoreBaselines(accounts []types.Account) {
|
||||
defer wg.Done()
|
||||
limit <- struct{}{}
|
||||
defer func() { <-limit }()
|
||||
cli := s.clientForAccount(account.Name)
|
||||
if cli == nil {
|
||||
logger.LogAccountEvent("账号", "warn", account.Name, "积分基线查询失败: 账号=%s 没有可用客户端", account.Name)
|
||||
return
|
||||
}
|
||||
score, err := cli.Score(account.Cookie)
|
||||
if err != nil {
|
||||
logger.LogAccountEvent("账号", "warn", account.Name, "积分基线查询失败: 账号=%s err=%v", account.Name, err)
|
||||
@@ -649,22 +689,29 @@ func (s *Scheduler) FetchScoreBaselines(accounts []types.Account) {
|
||||
}
|
||||
|
||||
// logNetworkSummary 输出本次任务期间各类接口的聚合统计,替代逐条刷屏的网络日志。
|
||||
func (s *Scheduler) logNetworkSummary(cli *client.DouyuClient) {
|
||||
if cli == nil {
|
||||
return
|
||||
}
|
||||
for _, stat := range cli.RequestStats() {
|
||||
avg := time.Duration(0)
|
||||
if stat.Count > 0 {
|
||||
avg = stat.Total / time.Duration(stat.Count)
|
||||
}
|
||||
if stat.LastErr != "" {
|
||||
logger.LogEvent("网络", "info", "接口统计: %s ×%d 失败%d 平均=%s 最慢=%s 最后错误=%s",
|
||||
stat.Label, stat.Count, stat.Failed, utils.RoundDuration(avg), utils.RoundDuration(stat.Slowest), stat.LastErr)
|
||||
func (s *Scheduler) logNetworkSummary() {
|
||||
clients := s.allClients()
|
||||
for index, cli := range clients {
|
||||
if cli == nil {
|
||||
continue
|
||||
}
|
||||
logger.LogEvent("网络", "info", "接口统计: %s ×%d 失败%d 平均=%s 最慢=%s",
|
||||
stat.Label, stat.Count, stat.Failed, utils.RoundDuration(avg), utils.RoundDuration(stat.Slowest))
|
||||
label := "基础客户端"
|
||||
if index > 0 {
|
||||
label = fmt.Sprintf("代理组%d", index)
|
||||
}
|
||||
for _, stat := range cli.RequestStats() {
|
||||
avg := time.Duration(0)
|
||||
if stat.Count > 0 {
|
||||
avg = stat.Total / time.Duration(stat.Count)
|
||||
}
|
||||
if stat.LastErr != "" {
|
||||
logger.LogEvent("网络", "info", "%s接口统计: %s ×%d 失败%d 平均=%s 最慢=%s 最后错误=%s",
|
||||
label, stat.Label, stat.Count, stat.Failed, utils.RoundDuration(avg), utils.RoundDuration(stat.Slowest), stat.LastErr)
|
||||
continue
|
||||
}
|
||||
logger.LogEvent("网络", "info", "%s接口统计: %s ×%d 失败%d 平均=%s 最慢=%s",
|
||||
label, stat.Label, stat.Count, stat.Failed, utils.RoundDuration(avg), utils.RoundDuration(stat.Slowest))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1095,6 +1142,14 @@ func (s *Scheduler) RunXiaodian(accountProducts map[string]string, attempts, del
|
||||
logger.LogEvent("抢购", "warn", "和平小店抢购没有可执行账号")
|
||||
return
|
||||
}
|
||||
accountProductsForProxy := make(map[string]string, len(accounts))
|
||||
for _, account := range accounts {
|
||||
accountProductsForProxy[account.Name] = products[account.Name].CommodityID
|
||||
}
|
||||
if err := s.prepareProxyGroups(accountProductsForProxy, false); err != nil {
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次和平小店抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
s.startXiaodianReport(accounts, products, reportSessionID)
|
||||
|
||||
stoppedAccounts := make(map[string]string)
|
||||
|
||||
@@ -20,6 +20,11 @@ type scoreBaselineEntry struct {
|
||||
At int64 `json:"at"` // Unix 秒,便于判断基线有多旧
|
||||
}
|
||||
|
||||
type scoreBaselineJob struct {
|
||||
snapshot map[string]scoreBaselineEntry
|
||||
ack chan struct{}
|
||||
}
|
||||
|
||||
// ScoreBaselineStore 记录每个账号"上次已知的积分余额",作为抢购结束后核对的基线。
|
||||
//
|
||||
// 刻意不在抢购链路里取基线:账号多的时候,预热或触发时刻的任何额外请求都会挤占抢购。
|
||||
@@ -35,7 +40,7 @@ type ScoreBaselineStore struct {
|
||||
entries map[string]scoreBaselineEntry
|
||||
|
||||
// flushCh 承接待落盘的快照;后台协程串行写盘,避免并发写互相覆盖。
|
||||
flushCh chan map[string]scoreBaselineEntry
|
||||
flushCh chan scoreBaselineJob
|
||||
// done 在关闭时等待后台写盘结束,保证退出前不丢数据。
|
||||
done chan struct{}
|
||||
// closeMu 保护 flushCh 的发送与关闭,避免"关闭后发送"导致 panic。
|
||||
@@ -51,7 +56,7 @@ func NewScoreBaselineStore(path string) *ScoreBaselineStore {
|
||||
entries: make(map[string]scoreBaselineEntry),
|
||||
}
|
||||
if path != "" {
|
||||
store.flushCh = make(chan map[string]scoreBaselineEntry, 8)
|
||||
store.flushCh = make(chan scoreBaselineJob, 8)
|
||||
store.done = make(chan struct{})
|
||||
go store.flushLoop()
|
||||
}
|
||||
@@ -64,8 +69,13 @@ func NewScoreBaselineStore(path string) *ScoreBaselineStore {
|
||||
// 队列满了就丢弃旧快照(写入最新状态即可),绝不让抢购侧阻塞等待。
|
||||
func (s *ScoreBaselineStore) flushLoop() {
|
||||
defer close(s.done)
|
||||
for snapshot := range s.flushCh {
|
||||
s.writeFile(snapshot)
|
||||
for job := range s.flushCh {
|
||||
if job.snapshot != nil {
|
||||
s.writeFile(job.snapshot)
|
||||
}
|
||||
if job.ack != nil {
|
||||
close(job.ack)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,14 +108,21 @@ func (s *ScoreBaselineStore) enqueue(snapshot map[string]scoreBaselineEntry) {
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
s.enqueueLocked(scoreBaselineJob{snapshot: snapshot})
|
||||
}
|
||||
|
||||
func (s *ScoreBaselineStore) enqueueLocked(job scoreBaselineJob) {
|
||||
for {
|
||||
select {
|
||||
case s.flushCh <- snapshot:
|
||||
case s.flushCh <- job:
|
||||
return
|
||||
default:
|
||||
// 队列满:丢掉最旧的一份,腾出位置放最新的。
|
||||
select {
|
||||
case <-s.flushCh:
|
||||
case dropped := <-s.flushCh:
|
||||
if dropped.ack != nil {
|
||||
close(dropped.ack)
|
||||
}
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -222,6 +239,19 @@ func (s *ScoreBaselineStore) Flush() {
|
||||
if s == nil || s.path == "" {
|
||||
return
|
||||
}
|
||||
if s.flushCh != nil {
|
||||
ack := make(chan struct{})
|
||||
s.closeMu.Lock()
|
||||
if !s.closed {
|
||||
s.enqueueLocked(scoreBaselineJob{ack: ack})
|
||||
} else {
|
||||
ack = nil
|
||||
}
|
||||
s.closeMu.Unlock()
|
||||
if ack != nil {
|
||||
<-ack
|
||||
}
|
||||
}
|
||||
s.mu.RLock()
|
||||
snapshot := make(map[string]scoreBaselineEntry, len(s.entries))
|
||||
for name, entry := range s.entries {
|
||||
|
||||
@@ -51,7 +51,6 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
|
||||
logger.LogEvent("预热", "info", "开始预热: %d 个账号", len(attempts))
|
||||
|
||||
settings := s.settingsSnapshot()
|
||||
cli := s.clientSnapshot()
|
||||
limit := make(chan struct{}, settings.concurrency)
|
||||
var wg sync.WaitGroup
|
||||
for _, attempt := range attempts {
|
||||
@@ -60,6 +59,11 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
|
||||
defer wg.Done()
|
||||
limit <- struct{}{}
|
||||
defer func() { <-limit }()
|
||||
cli := s.clientForAccount(attempt.Account.Name)
|
||||
if cli == nil {
|
||||
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "预热跳过: 账号=%s 没有可用客户端", attempt.Account.Name)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
csrf, err := cli.GenerateCSRF(attempt.Account.Cookie)
|
||||
|
||||
Reference in New Issue
Block a user