优化抢购流程日志和复验性能
This commit is contained in:
+126
-46
@@ -25,17 +25,21 @@ import (
|
||||
const (
|
||||
warmupBeforeTrigger = 2 * time.Second
|
||||
warmupMaxAge = 30 * time.Second
|
||||
qualifiedMaxAge = 30 * time.Second
|
||||
timeCalibrateRounds = 3
|
||||
timeCalibrateWait = 1200 * time.Millisecond
|
||||
resyncBeforeTrigger = 10 * time.Second
|
||||
seckillMaxDuration = 75 * time.Second
|
||||
behaviorCooldown = 8 * time.Second
|
||||
clickFastCooldown = 3 * time.Second
|
||||
)
|
||||
|
||||
type roundOutcome struct {
|
||||
successAccounts map[string]bool
|
||||
stoppedAccounts map[string]string
|
||||
stoppedProducts map[string]string
|
||||
attempts int
|
||||
successAccounts map[string]bool
|
||||
stoppedAccounts map[string]string
|
||||
stoppedProducts map[string]string
|
||||
cooldownAccounts map[string]time.Time
|
||||
attempts int
|
||||
}
|
||||
|
||||
// Scheduler 抢购调度器。
|
||||
@@ -295,12 +299,18 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
successAccounts := make(map[string]bool)
|
||||
stoppedAccounts := make(map[string]string)
|
||||
stoppedProducts := make(map[string]string)
|
||||
cooldownAccounts := make(map[string]time.Time)
|
||||
totalAccounts := uniqueAttemptAccounts(allAttempts)
|
||||
totalAttempts := 0
|
||||
startTime := time.Now()
|
||||
round := 0
|
||||
|
||||
logger.LogEvent("抢购", "info", "开始抢购: %d 个账号,窗口=%v,前段高频后段降速", totalAccounts, seckillMaxDuration)
|
||||
s.clearAttemptCache()
|
||||
if s.seckillMode == types.SeckillModeAggressive {
|
||||
s.initCacheFromWarmup(allAttempts)
|
||||
}
|
||||
|
||||
logger.LogEvent("抢购", "info", "开始抢购: %d 个账号,窗口=%v,预检通过后直兑,前段高频后段降速", totalAccounts, seckillMaxDuration)
|
||||
|
||||
for {
|
||||
elapsed := time.Since(startTime)
|
||||
@@ -324,13 +334,21 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
break
|
||||
}
|
||||
|
||||
// 激进模式每轮开始时清空缓存,强制重新获取 CSRF
|
||||
if s.seckillMode == types.SeckillModeAggressive {
|
||||
s.clearAttemptCache()
|
||||
// 第1轮时从预热数据初始化缓存
|
||||
if round == 1 {
|
||||
s.initCacheFromWarmup(roundAttempts)
|
||||
now := time.Now()
|
||||
roundAttempts, nextReady := filterCooldownAttempts(roundAttempts, cooldownAccounts, now)
|
||||
if len(roundAttempts) == 0 {
|
||||
sleepFor := nextReady.Sub(now)
|
||||
if sleepFor <= 0 {
|
||||
sleepFor = s.getRetryInterval(time.Since(startTime))
|
||||
}
|
||||
if sleepFor > remaining {
|
||||
sleepFor = remaining
|
||||
}
|
||||
if sleepFor > 0 {
|
||||
logger.LogEvent("抢购", "info", "第%d轮账号冷却中,等待=%v", round, utils.RoundDuration(sleepFor))
|
||||
time.Sleep(sleepFor)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
logger.LogEvent("抢购", "info", "第%d轮: 待抢购 %d 个账号,本轮执行=%d,剩余时间=%v,模式=%s",
|
||||
@@ -355,6 +373,13 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
logger.LogEvent("抢购", "warn", "商品停止重试: %s,原因=%s", product, reason)
|
||||
}
|
||||
}
|
||||
for account, until := range outcome.cooldownAccounts {
|
||||
if until.After(cooldownAccounts[account]) {
|
||||
cooldownAccounts[account] = until
|
||||
logger.LogAccountEvent("抢购", "warn", account, "账号临时降频: 账号=%s 冷却至=%s",
|
||||
account, until.In(constants.CST).Format("15:04:05.000"))
|
||||
}
|
||||
}
|
||||
|
||||
if len(outcome.successAccounts) > 0 {
|
||||
logger.LogEvent("抢购", "success", "第%d轮成功: %d 个账号", round, len(outcome.successAccounts))
|
||||
@@ -389,6 +414,22 @@ func (s *Scheduler) filterPendingAttempts(allAttempts []types.ExchangeAttempt, s
|
||||
return pending
|
||||
}
|
||||
|
||||
func filterCooldownAttempts(attempts []types.ExchangeAttempt, cooldownAccounts map[string]time.Time, now time.Time) ([]types.ExchangeAttempt, time.Time) {
|
||||
out := make([]types.ExchangeAttempt, 0, len(attempts))
|
||||
var nextReady time.Time
|
||||
for _, attempt := range attempts {
|
||||
until := cooldownAccounts[attempt.Account.Name]
|
||||
if until.After(now) {
|
||||
if nextReady.IsZero() || until.Before(nextReady) {
|
||||
nextReady = until
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, attempt)
|
||||
}
|
||||
return out, nextReady
|
||||
}
|
||||
|
||||
// pickRoundAttempts 每轮每个账号最多执行一次,避免同账号并发过猛触发频控。
|
||||
func (s *Scheduler) pickRoundAttempts(attempts []types.ExchangeAttempt, round int) []types.ExchangeAttempt {
|
||||
if len(attempts) == 0 {
|
||||
@@ -427,9 +468,10 @@ func (s *Scheduler) pickRoundAttempts(attempts []types.ExchangeAttempt, round in
|
||||
// executeRound 执行一轮抢购,并返回成功和终止重试的账号。
|
||||
func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome {
|
||||
outcome := roundOutcome{
|
||||
successAccounts: make(map[string]bool),
|
||||
stoppedAccounts: make(map[string]string),
|
||||
stoppedProducts: make(map[string]string),
|
||||
successAccounts: make(map[string]bool),
|
||||
stoppedAccounts: make(map[string]string),
|
||||
stoppedProducts: make(map[string]string),
|
||||
cooldownAccounts: make(map[string]time.Time),
|
||||
}
|
||||
var mu sync.Mutex
|
||||
|
||||
@@ -459,14 +501,19 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome
|
||||
mu.Unlock()
|
||||
|
||||
if result.OK {
|
||||
logger.LogEvent("抢购", "success", "成功: %s %s 第%d包 %s", result.Account, result.Product, result.Attempt, result.Message)
|
||||
logger.LogAccountEvent("抢购", "success", result.Account, "成功: 账号=%s 商品=%s 第%d包 %s", result.Account, result.Product, result.Attempt, result.Message)
|
||||
go image.SaveSuccessImage(attempt.Account, attempt.Product, result.RoleName, s.font, s.paths.SuccessDir)
|
||||
|
||||
mu.Lock()
|
||||
outcome.successAccounts[attempt.Account.Name] = true
|
||||
mu.Unlock()
|
||||
} else {
|
||||
logger.LogEvent("抢购", "info", "尝试: %s %s 第%d包 %s", result.Account, result.Product, result.Attempt, result.Message)
|
||||
logger.LogAccountEvent("抢购", "info", result.Account, "尝试: 账号=%s 商品=%s 第%d包 %s", result.Account, result.Product, result.Attempt, result.Message)
|
||||
if cooldown := retryCooldownDuration(result.Message); cooldown > 0 {
|
||||
mu.Lock()
|
||||
outcome.cooldownAccounts[attempt.Account.Name] = time.Now().Add(jitterDuration(cooldown))
|
||||
mu.Unlock()
|
||||
}
|
||||
terminalAccount, terminalProduct, isSuccess, reason := classifyRetryStop(result.Message)
|
||||
if terminalAccount || terminalProduct {
|
||||
mu.Lock()
|
||||
@@ -479,7 +526,7 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt) roundOutcome
|
||||
// 兑换上限也算成功
|
||||
if isSuccess {
|
||||
outcome.successAccounts[attempt.Account.Name] = true
|
||||
logger.LogEvent("抢购", "success", "成功(兑换上限): %s %s 第%d包", result.Account, result.Product, result.Attempt)
|
||||
logger.LogAccountEvent("抢购", "success", result.Account, "成功(兑换上限): 账号=%s 商品=%s 第%d包", result.Account, result.Product, result.Attempt)
|
||||
go image.SaveSuccessImage(attempt.Account, attempt.Product, result.RoleName, s.font, s.paths.SuccessDir)
|
||||
}
|
||||
mu.Unlock()
|
||||
@@ -524,6 +571,17 @@ func jitterDuration(base time.Duration) time.Duration {
|
||||
return base + jitter
|
||||
}
|
||||
|
||||
func retryCooldownDuration(message string) time.Duration {
|
||||
switch {
|
||||
case strings.Contains(message, "用户行为异常"):
|
||||
return behaviorCooldown
|
||||
case strings.Contains(message, "点击太快"):
|
||||
return clickFastCooldown
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func classifyRetryStop(message string) (account bool, product bool, success bool, reason string) {
|
||||
switch {
|
||||
case strings.Contains(message, "商品本次活动库存已耗完"):
|
||||
@@ -612,9 +670,10 @@ func (s *Scheduler) initCacheFromWarmup(attempts []types.ExchangeAttempt) {
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: warmup.CSRF,
|
||||
RoleName: warmup.RoleName,
|
||||
Qualified: warmup.Qualified,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
logger.LogEvent("抢购", "info", "从预热初始化缓存: 账号=%s", attempt.Account.Name)
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "从预热初始化缓存: 账号=%s", attempt.Account.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,6 +681,10 @@ func (s *Scheduler) initCacheFromWarmup(attempts []types.ExchangeAttempt) {
|
||||
func (s *Scheduler) setAttemptCache(accountName string, cache *types.AttemptCache) {
|
||||
s.attemptCacheMu.Lock()
|
||||
defer s.attemptCacheMu.Unlock()
|
||||
if cache == nil {
|
||||
delete(s.attemptCache, accountName)
|
||||
return
|
||||
}
|
||||
s.attemptCache[accountName] = cache
|
||||
}
|
||||
|
||||
@@ -631,13 +694,6 @@ func (s *Scheduler) clearAttemptCache() {
|
||||
s.attemptCache = make(map[string]*types.AttemptCache)
|
||||
}
|
||||
|
||||
func (s *Scheduler) getCacheCSRF(accountName string) string {
|
||||
if cache := s.getAttemptCache(accountName); cache != nil && time.Since(cache.LastCheck) < 30*time.Second {
|
||||
return cache.CSRF
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
|
||||
if len(attempts) == 0 {
|
||||
return
|
||||
@@ -657,19 +713,19 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
|
||||
start := time.Now()
|
||||
csrf, err := s.client.GenerateCSRF(attempt.Account.Cookie)
|
||||
if err != nil {
|
||||
logger.LogEvent("预热", "warn", "CSRF预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err)
|
||||
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "CSRF预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err)
|
||||
return
|
||||
}
|
||||
roleName, err := s.client.RoleName(attempt.Account.Cookie)
|
||||
if err != nil {
|
||||
logger.LogEvent("预热", "warn", "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||||
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||||
}
|
||||
s.setWarmup(warmupKey(attempt), types.WarmupData{
|
||||
CSRF: csrf,
|
||||
RoleName: roleName,
|
||||
CreatedAt: time.Now(),
|
||||
})
|
||||
logger.LogEvent("预热", "success", "预热完成: 账号=%s 商品=%s 耗时=%s", attempt.Account.Name, attempt.Product.CommodityName, utils.RoundDuration(time.Since(start)))
|
||||
logger.LogAccountEvent("预热", "success", attempt.Account.Name, "预热完成: 账号=%s 商品=%s 耗时=%s", attempt.Account.Name, attempt.Product.CommodityName, utils.RoundDuration(time.Since(start)))
|
||||
}(attempt)
|
||||
}
|
||||
wg.Wait()
|
||||
@@ -721,13 +777,13 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
Attempt: attempt.Index,
|
||||
}
|
||||
|
||||
logger.LogEvent("抢购", "info", "执行兑换链路: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "执行资格预检链路: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
|
||||
var roleName string
|
||||
csrf := ""
|
||||
if warmup, ok := s.warmupFor(attempt); ok {
|
||||
csrf = warmup.CSRF
|
||||
roleName = warmup.RoleName
|
||||
logger.LogEvent("抢购", "info", "使用预热CSRF: 账号=%s 商品=%s 预热距今=%s", attempt.Account.Name, attempt.Product.CommodityName, utils.RoundDuration(time.Since(warmup.CreatedAt)))
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "使用预热CSRF: 账号=%s 商品=%s 预热距今=%s", attempt.Account.Name, attempt.Product.CommodityName, utils.RoundDuration(time.Since(warmup.CreatedAt)))
|
||||
}
|
||||
if csrf == "" {
|
||||
var err error
|
||||
@@ -736,7 +792,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
result.Message = "失败|生成CSRF失败: " + err.Error()
|
||||
return result
|
||||
}
|
||||
logger.LogEvent("抢购", "info", "CSRF已生成,本次兑换链路复用同一个 token: 账号=%s 商品=%s", attempt.Account.Name, attempt.Product.CommodityName)
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "CSRF已生成,本次兑换链路复用同一个 token: 账号=%s 商品=%s", attempt.Account.Name, attempt.Product.CommodityName)
|
||||
}
|
||||
|
||||
limit, err := s.client.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
|
||||
@@ -748,15 +804,28 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
result.Message = "失败|当前商品限制兑换"
|
||||
return result
|
||||
}
|
||||
logger.LogEvent("抢购", "info", "批量限制通过: 账号=%s 商品=%s limit=%d", attempt.Account.Name, attempt.Product.CommodityName, limit)
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "批量限制通过: 账号=%s 商品=%s limit=%d", attempt.Account.Name, attempt.Product.CommodityName, limit)
|
||||
|
||||
if err := s.client.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil {
|
||||
result.Message = "失败|预兑换失败: " + err.Error()
|
||||
return result
|
||||
}
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: csrf,
|
||||
RoleName: roleName,
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "资格预检通过: 账号=%s 商品=%s,后续可直兑", attempt.Account.Name, attempt.Product.CommodityName)
|
||||
|
||||
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
|
||||
if err != nil {
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: csrf,
|
||||
RoleName: roleName,
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
result.Message = "失败|" + err.Error()
|
||||
return result
|
||||
}
|
||||
@@ -764,7 +833,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
if roleName == "" {
|
||||
roleName, err = s.client.RoleName(attempt.Account.Cookie)
|
||||
if err != nil {
|
||||
logger.LogEvent("抢购", "warn", "%s 角色名查询失败: %v", attempt.Account.Name, err)
|
||||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -780,6 +849,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: csrf,
|
||||
RoleName: roleName,
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
|
||||
@@ -794,23 +864,32 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
|
||||
Attempt: attempt.Index,
|
||||
}
|
||||
|
||||
// 获取缓存的 CSRF
|
||||
csrf := s.getCacheCSRF(attempt.Account.Name)
|
||||
if csrf == "" {
|
||||
// 没有缓存,回退到标准模式
|
||||
logger.LogEvent("抢购", "info", "激进模式回退标准: 账号=%s 原因=无缓存CSRF", attempt.Account.Name)
|
||||
cache := s.getAttemptCache(attempt.Account.Name)
|
||||
if cache == nil || cache.CSRF == "" || time.Since(cache.LastCheck) >= qualifiedMaxAge {
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式执行资格预检: 账号=%s 原因=无缓存CSRF", attempt.Account.Name)
|
||||
return s.runAttempt(attempt)
|
||||
}
|
||||
if !cache.Qualified {
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式执行资格预检: 账号=%s 原因=未完成资格预检", attempt.Account.Name)
|
||||
return s.runAttempt(attempt)
|
||||
}
|
||||
|
||||
logger.LogEvent("抢购", "info", "激进模式兑换: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
|
||||
csrf := cache.CSRF
|
||||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式直兑: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
|
||||
|
||||
// 直接调用 Exchange
|
||||
exchangeInfo, err := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
|
||||
if err != nil {
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: csrf,
|
||||
RoleName: cache.RoleName,
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
errMsg := err.Error()
|
||||
// 检查是否是 CSRF 相关错误,如果是则回退到标准模式
|
||||
if strings.Contains(errMsg, "csrf") || strings.Contains(errMsg, "CSRF") || strings.Contains(errMsg, "token") {
|
||||
logger.LogEvent("抢购", "warn", "激进模式回退标准: 账号=%s 原因=CSRF错误", attempt.Account.Name)
|
||||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "激进模式回退标准: 账号=%s 原因=CSRF错误", attempt.Account.Name)
|
||||
s.setAttemptCache(attempt.Account.Name, nil) // 清空缓存
|
||||
return s.runAttempt(attempt)
|
||||
}
|
||||
@@ -819,7 +898,6 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
|
||||
}
|
||||
|
||||
// 获取角色名
|
||||
cache := s.getAttemptCache(attempt.Account.Name)
|
||||
roleName := ""
|
||||
if cache != nil {
|
||||
roleName = cache.RoleName
|
||||
@@ -828,13 +906,15 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
|
||||
var err error
|
||||
roleName, err = s.client.RoleName(attempt.Account.Cookie)
|
||||
if err != nil {
|
||||
logger.LogEvent("抢购", "warn", "%s 角色名查询失败: %v", attempt.Account.Name, err)
|
||||
}
|
||||
// 更新缓存
|
||||
if cache != nil {
|
||||
cache.RoleName = roleName
|
||||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||||
}
|
||||
}
|
||||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||||
CSRF: csrf,
|
||||
RoleName: roleName,
|
||||
Qualified: true,
|
||||
LastCheck: time.Now(),
|
||||
})
|
||||
|
||||
result.OK = true
|
||||
result.RoleName = roleName
|
||||
|
||||
Reference in New Issue
Block a user