重构锁单支付重试内核并修复多实例启动,发布0.3.0

- 抢购内核改为"每账号独立重试循环",移除轮次屏障:旧实现在 3 个中签账号卡住
  60 秒支付退避时,另外 31 个账号空转 39 秒,还出现过"某一轮只跑 1 个账号、其余整轮没被尝试"
- 锁单退避改为读取配置的"重试间隔策略"(同一账号连续失败成倍放大,封顶 5 秒),
  删掉硬编码 30 秒退避与"只重试一次"
- 锁单失败不再提前停止:限流(活动火爆/网络繁忙)继续重试;售罄也继续降频探测
  (别人锁单后支付失败或锁单过期,库存会回流),只在窗口结束时按售罄/限流/普通失败分类上报
- 支付重试按斗鱼错误码决策:1644430001/1644400002/1644400014 视为"订单已受理、结果未定"
  并快重试(300ms 起),取代按文案把"订单操作进行中"误判成频控的 60 秒退避;
  不再设次数上限,只受 120 秒预算与锁单过期约束,超出预算如实报"支付结果未知"
- 已锁订单在 75 秒窗口结束后仍会支付完,不再受窗口约束
- 多实例:为每个实例分配独占的 WebView2 用户数据目录。Wails 默认所有实例共用
  %APPDATA%\<可执行文件名>,而一个数据目录只能有一个浏览器进程,导致偶发开不出新实例、
  必须全部关掉重开;实例占位因此提前到 wails.Run 之前完成
- 多实例:占位失败不再静默退回默认目录(会让两个进程共享 accounts.txt/config.json、
  同秒启动还会写同一个日志文件),改为进程唯一的临时实例目录并记录降级原因
- 多实例:单个槽位锁被瞬时占用(杀软/索引器)时短暂重试,仍失败则继续试下一个槽位
  而不是整个分配失败;日志文件改为独占创建,同秒启动自动追加 -2/-3 后缀
- 新增 %LOCALAPPDATA%\douyu-go\startup.log,记录每次启动与失败原因,
  便于排查"窗口起不来"这类连应用日志都不会生成的问题
- 修复预热缓存日志每个账号打两遍、"账号尝试"计数误导(改为真实锁单/支付/直接兑换次数)
- 修复前端把含"成功"字样的失败文案显示成抢到(改为只认"成功|"前缀)
- 修复 jitterDuration 在基准小于 10ms 时 rand.Int63n(0) 会 panic 的隐患
- 设置页文案与作用域同步:重试间隔策略明确作用于锁单重试、"尝试包数"明确仅用于和平小店
This commit is contained in:
yml2213
2026-10-03 19:09:19 +08:00
parent 1f76c12b48
commit 46c06180a5
18 changed files with 1791 additions and 564 deletions
+300 -291
View File
@@ -2,7 +2,6 @@ package seckill
import (
"fmt"
"math/rand"
"sort"
"strings"
"sync"
@@ -26,12 +25,15 @@ const (
timeCalibrateWait = 1200 * time.Millisecond
resyncBeforeTrigger = 3 * time.Second
calibrationHistorySize = 3
seckillMaxDuration = 75 * time.Second
minInternalAdvance = 50 * time.Millisecond
maxCooldownCount = 5
xiaodianDefaultDelay = 500 * time.Millisecond
)
// seckillMaxDuration 是手册类活动的抢购窗口:超过后不再发起新的锁单。
// 声明为变量是为了让测试能缩短窗口。
var seckillMaxDuration = 75 * time.Second
type roundOutcome struct {
successAccounts map[string]bool
stoppedAccounts map[string]string
@@ -400,216 +402,308 @@ func (s *Scheduler) interruptibleSleep(d time.Duration) bool {
}
}
// RunNow 立即执行抢购任务,持续循环直到超时或全部成功。
// RunNow 立即执行手册类活动的抢购任务(精英手册锁单支付 / 电竞手册直接兑换)。
//
// 每个账号在自己的 goroutine 中独立重试,互不阻塞。早期版本用"轮次 + wg.Wait"
// 把所有账号绑在一起:3 个中签账号卡在 60 秒支付退避时,另外 31 个账号白白空转
// 39 秒(2026-10-03 日志实测),还出现过"某一轮只跑了 1 个账号、其余 33 个整轮
// 没被尝试"的退化。
//
// 窗口硬约束:到 seckillMaxDuration 后不再发起新的锁单;已经锁单成功的账号
// 仍会把支付做完(支付阶梯只受停止指令和锁单过期约束,放弃等于白锁)。
func (s *Scheduler) RunNow(accountProducts map[string]string) {
defer s.finishRun()
s.ClearResults()
settings := s.settingsSnapshot()
allAttempts := s.buildAttempts(accountProducts, settings.attempts)
if len(allAttempts) == 0 {
tasks := s.buildTasks(accountProducts)
if len(tasks) == 0 {
logger.LogEvent("抢购", "warn", "没有可执行的抢购任务")
return
}
successAccounts := make(map[string]bool)
stoppedAccounts := make(map[string]string)
stoppedProducts := make(map[string]string)
cooldownAccounts := make(map[string]time.Time)
cooldownCount := make(map[string]int)
totalAccounts := uniqueAttemptAccounts(allAttempts)
totalAttempts := 0
startTime := time.Now()
round := 0
start := time.Now()
deadline := start.Add(seckillMaxDuration)
ctl := newRunControl(s, start, deadline, settings.concurrency)
s.clearAttemptCache()
if settings.seckillMode == types.SeckillModeAggressive {
s.initCacheFromWarmup(allAttempts)
s.initCacheFromWarmup(tasks)
}
logger.LogEvent("抢购", "info", "开始抢购: %d 个账号,窗口=%v", totalAccounts, seckillMaxDuration)
for {
if s.runStopped() {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
elapsed := time.Since(startTime)
if elapsed >= seckillMaxDuration {
logger.LogEvent("抢购", "info", "已达到抢购窗口 %v,停止抢购", seckillMaxDuration)
break
}
round++
remaining := seckillMaxDuration - elapsed
pendingAttempts := s.filterPendingAttempts(allAttempts, stoppedAccounts, stoppedProducts)
if len(pendingAttempts) == 0 {
logger.LogEvent("抢购", "info", "所有账号都已成功或遇到终止条件,停止抢购")
break
}
roundAttempts := pickRoundAttempts(pendingAttempts, round, settings.attempts)
if len(roundAttempts) == 0 {
logger.LogEvent("抢购", "info", "第%d轮无可执行账号,停止抢购", round)
break
}
now := time.Now()
roundAttempts, nextReady := filterCooldownAttempts(roundAttempts, cooldownAccounts, now)
if len(roundAttempts) == 0 {
sleepFor := nextReady.Sub(now)
if sleepFor <= 0 {
sleepFor = retryIntervalFor(settings.retryStages, time.Since(startTime))
}
if sleepFor > remaining {
sleepFor = remaining
}
if sleepFor > 0 {
logger.LogEvent("抢购", "info", "第%d轮账号冷却中,等待=%v", round, utils.RoundDuration(sleepFor))
if s.interruptibleSleep(sleepFor) {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
}
continue
}
logger.LogEvent("抢购", "info", "第%d轮: 待抢购 %d 个账号,本轮执行=%d,剩余时间=%v,模式=%s",
round, uniqueAttemptAccounts(pendingAttempts), len(roundAttempts), utils.RoundDuration(remaining),
modeName(settings.seckillMode))
outcome := s.executeRound(roundAttempts, settings)
totalAttempts += outcome.attempts
for account := range outcome.successAccounts {
successAccounts[account] = true
stoppedAccounts[account] = "已抢到"
}
for account, reason := range outcome.stoppedAccounts {
if stoppedAccounts[account] == "" {
stoppedAccounts[account] = reason
logger.LogAccountEvent("抢购", "warn", account, "账号停止重试: 账号=%s 原因=%s", account, reason)
}
}
for product, reason := range outcome.stoppedProducts {
if stoppedProducts[product] == "" {
stoppedProducts[product] = reason
logger.LogEvent("抢购", "warn", "商品停止重试: %s,原因=%s", product, reason)
}
}
for account, until := range outcome.cooldownAccounts {
if until.After(cooldownAccounts[account]) {
cooldownAccounts[account] = until
cooldownCount[account]++
logger.LogAccountEvent("抢购", "warn", account, "账号临时降频: 账号=%s 冷却至=%s (第%d次)",
account, until.In(constants.CST).Format("15:04:05.000"), cooldownCount[account])
if cooldownCount[account] >= maxCooldownCount {
stoppedAccounts[account] = "冷却次数过多"
logger.LogAccountEvent("抢购", "warn", account, "账号停止重试: 账号=%s 原因=冷却次数过多(%d次)", account, cooldownCount[account])
}
}
}
if s.runStopped() {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
if len(outcome.successAccounts) > 0 {
logger.LogEvent("抢购", "success", "第%d轮成功: %d 个账号", round, len(outcome.successAccounts))
}
if len(stoppedAccounts) >= totalAccounts {
logger.LogEvent("抢购", "info", "所有账号都已成功或停止重试,停止抢购")
break
}
retryInterval := retryIntervalFor(settings.retryStages, time.Since(startTime))
if retryInterval > 0 && time.Since(startTime)+retryInterval < seckillMaxDuration {
if s.interruptibleSleep(jitterDuration(retryInterval)) {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
}
logger.LogEvent("抢购", "info", "开始抢购: %d 个账号,窗口=%v,截止=%s",
len(tasks), seckillMaxDuration, deadline.In(constants.CST).Format("15:04:05.000"))
for _, target := range productTargets(tasks) {
logger.LogEvent("抢购", "info", "抢购目标: %s", target)
}
logger.LogEvent("抢购", "info", "抢购任务结束: 成功=%d/%d,停止=%d,账号尝试=%d,耗时=%v",
len(successAccounts), totalAccounts, len(stoppedAccounts)-len(successAccounts), totalAttempts, utils.RoundDuration(time.Since(startTime)))
outcomes := make([]accountOutcome, len(tasks))
var wg sync.WaitGroup
for i, task := range tasks {
wg.Add(1)
go func(index int, task types.ExchangeAttempt) {
defer wg.Done()
outcomes[index] = s.runAccountLoop(task, settings, ctl)
}(i, task)
}
wg.Wait()
s.logRunSummary(outcomes, ctl, time.Since(start))
}
// RunFixed 按固定轮数和轮间隔抢购,账号成功后不再参与后续轮次。
func (s *Scheduler) RunFixed(accountProducts map[string]string, attempts, delayMs int) {
defer s.finishRun()
s.ClearResults()
settings := s.settingsSnapshot()
if attempts < 1 {
attempts = 1
// 账号最终结束状态。
const (
outcomeSuccess = "success"
outcomeRejected = "rejected" // 窗口结束时商品始终售罄
outcomeThrottled = "throttled" // 窗口内始终被请求级限流
outcomeTerminal = "terminal" // 命中账号级终止条件
outcomeLockedUnpaid = "lockedUnpaid" // 已锁单成功但支付未完成
outcomeStopped = "stopped"
outcomeExpired = "expired"
)
// 每账号重试节奏的上下限与递增倍数。
const (
minRetryDelay = 100 * time.Millisecond
maxRetryDelay = 5 * time.Second
maxRetryEscalation = 8
)
// stockOutWarnAfter 是同一账号连续收到"商品已售罄"多少次后,打一条"转为低频探测"
// 的提示日志。它只影响提示,不影响是否继续重试。
//
// 刻意不因售罄而停止:别人锁单后支付失败或锁单过期,占用的库存会回流,
// 窗口内必须继续探测(旧实现里就有"库存耗尽不停止,斗鱼可能会补货"的结论)。
// "活动火爆/网络繁忙"则连提示都不打——2026-10-03 日志里同一实例、同一秒内
// 3 个账号对同一个 commodityID 锁单成功而另外 31 个被拒,说明那只是请求级限流。
const stockOutWarnAfter = 8
// accountOutcome 是单个账号的最终结果。
type accountOutcome struct {
account string
kind string
reason string
locked bool
}
// runAccountLoop 是单个账号的独立重试循环:锁单失败按配置节奏重试,
// 达到连续被拒上限或账号级终止条件时退出。
func (s *Scheduler) runAccountLoop(task types.ExchangeAttempt, settings runSettings, ctl *runControl) accountOutcome {
out := accountOutcome{account: task.Account.Name}
// rejectStreak 只统计"该商品当前拿不到"的连续次数,用于停止判定;
// failStreak 统计所有连续失败,用于放大退避(两者混用会让频控/传输层错误
// 永远不递增,一路用配置里的最快节奏猛打)。
stockStreak := 0
stockOutWarned := false
failStreak := 0
attempts := 0
lastFailure := ""
lastStockOut := false
lastThrottled := false
for {
if ctl.stopped() {
out.kind, out.reason = outcomeStopped, "已收到停止指令"
return out
}
if ctl.expired() {
out.kind, out.reason = expiryOutcome(lastStockOut, lastThrottled, lastFailure)
if lastFailure != "" {
s.setResult(resultKey(task), "失败|"+out.reason)
}
return out
}
attempts++
task.Index = attempts
res := s.runAccountAttempt(task, settings.seckillMode, ctl)
out.locked = out.locked || res.locked
s.setResult(resultKey(task), res.result.Message)
if res.result.OK {
out.kind = outcomeSuccess
out.reason = res.result.Message
logger.LogAccountEvent("抢购", "success", out.account, "成功: 账号=%s 商品=%s 第%d次 %s",
out.account, res.result.Product, res.result.Attempt, res.result.Message)
s.enqueueSuccessImage(task.Account, task.Product, res.result.RoleName)
return out
}
if res.stopped {
out.kind, out.reason = outcomeStopped, "已收到停止指令"
return out
}
if res.terminal {
out.kind, out.reason = outcomeTerminal, failureReason(res.result.Message)
logger.LogAccountEvent("抢购", "warn", out.account, "账号停止重试: 账号=%s 原因=%s", out.account, out.reason)
return out
}
if res.locked {
// 已锁单成功但支付没有完成:不再新建锁单,避免重复下单。
out.kind, out.reason = outcomeLockedUnpaid, failureReason(res.result.Message)
logger.LogAccountEvent("抢购", "warn", out.account, "锁单已占用,不再新建锁单: 账号=%s 原因=%s", out.account, out.reason)
return out
}
failStreak++
lastFailure = failureReason(res.result.Message)
lastStockOut = res.stockOut
lastThrottled = res.throttled
if res.stockOut {
stockStreak++
} else {
stockStreak = 0
}
// 售罄不等于终态:别人锁单后支付失败或锁单过期,库存会回流,
// 所以窗口内一律继续探测,只是退避会随连续失败自动降到秒级。
if stockStreak == stockOutWarnAfter && !stockOutWarned {
stockOutWarned = true
logger.LogAccountEvent("抢购", "warn", out.account,
"商品疑似售罄,转为低频探测直到窗口结束: 账号=%s 商品=%s(%s) 连续%d次 %s",
out.account, task.Product.CommodityName, task.Product.CommodityID, stockStreak, lastFailure)
}
delay := retryDelay(settings.retryStages, ctl.elapsed(), failStreak)
logger.LogAccountEvent("抢购", "info", out.account, "第%d次未成功,%s 后重试: %s",
attempts, utils.RoundDuration(delay), lastFailure)
if !ctl.sleep(delay) {
if ctl.stopped() {
out.kind, out.reason = outcomeStopped, "已收到停止指令"
} else {
out.kind, out.reason = expiryOutcome(lastStockOut, lastThrottled, lastFailure)
// 把分类后的结束原因写进结果集,账号表才看得出"售罄/限流"而不是原始错误。
s.setResult(resultKey(task), "失败|"+out.reason)
}
return out
}
}
if attempts > 100000 {
attempts = 100000
}
// expiryOutcome 生成"抢购窗口结束"的结束原因,并带上最后一次失败。
//
// 必须区分售罄 / 被限流 / 普通失败:否则界面上只有一个孤零零的 0 成功,
// 看不出到底发生了什么(这正是 2026-10-03 的排查痛点)。
// 注意这里不提前停止——售罄后库存可能回流,必须探测到窗口结束。
func expiryOutcome(lastStockOut, lastThrottled bool, lastFailure string) (string, string) {
switch {
case lastFailure == "":
return outcomeExpired, "抢购窗口已结束"
case lastStockOut:
return outcomeRejected, "抢购窗口结束(商品始终售罄: " + lastFailure + ")"
case lastThrottled:
return outcomeThrottled, "抢购窗口结束(最后仍被限流: " + lastFailure + ")"
default:
return outcomeExpired, "抢购窗口结束(最后失败: " + lastFailure + ")"
}
if delayMs < 0 {
delayMs = 0
}
// retryDelay 计算账号下一次尝试前的等待时间。
//
// 基准节奏来自配置的"重试间隔策略"(按经过秒数分档)——早期版本把它只用在
// 轮与轮之间,单次锁单失败却硬编码睡 30 秒,配置形同虚设。同一账号连续失败时
// 再成倍放大,避免单个账号猛打;并叠加抖动,防止所有账号同步重试形成尖峰。
func retryDelay(stages []types.RetryStage, elapsed time.Duration, failStreak int) time.Duration {
base := retryIntervalFor(stages, elapsed)
if base <= 0 {
base = 900 * time.Millisecond
}
if delayMs > 60000 {
delayMs = 60000
mult := 1
for i := 1; i < failStreak && mult < maxRetryEscalation; i++ {
mult <<= 1
}
delay := time.Duration(mult) * base
if delay > maxRetryDelay {
delay = maxRetryDelay
}
if delay < minRetryDelay {
delay = minRetryDelay
}
return jitterFraction(delay, 2)
}
// resultKey 生成结果键。
//
// 后缀保持历史上的 `_第N包` 形态:前端 useLogs.ts / ControlStrip.vue 用
// /_第\d+包$/ 归并出账号名。这里固定第 1 包,保证每个账号只占一个结果条目
// ——早期实现每次尝试都写一个新键,重试几十次后结果集会膨胀到几千条。
func resultKey(attempt types.ExchangeAttempt) string {
return fmt.Sprintf("%s_第1包", attempt.Account.Name)
}
// failureReason 去掉结果里的"失败|"前缀,便于汇总展示。
func failureReason(message string) string {
return strings.TrimPrefix(message, "失败|")
}
// productTargets 汇总本次抢购的商品,并把 commodityID 打进日志。
// 2026-10-03 的排查正卡在"日志里没有 commodityID",无法判断各实例是否选了同一个 SKU。
func productTargets(tasks []types.ExchangeAttempt) []string {
order := make([]string, 0, 2)
names := make(map[string]string, 2)
counts := make(map[string]int, 2)
for _, task := range tasks {
id := task.Product.CommodityID
if _, ok := counts[id]; !ok {
order = append(order, id)
names[id] = task.Product.CommodityName
}
counts[id]++
}
out := make([]string, 0, len(order))
for _, id := range order {
out = append(out, fmt.Sprintf("商品=%s(%s) 账号=%d", names[id], id, counts[id]))
}
return out
}
// logRunSummary 输出按结束原因分类的汇总与真实请求次数。
func (s *Scheduler) logRunSummary(outcomes []accountOutcome, ctl *runControl, cost time.Duration) {
var success, rejected, throttled, terminal, lockedUnpaid, stopped, expired int
reasons := make(map[string]int)
for _, out := range outcomes {
switch out.kind {
case outcomeSuccess:
success++
case outcomeRejected:
rejected++
case outcomeThrottled:
throttled++
case outcomeTerminal:
terminal++
case outcomeLockedUnpaid:
lockedUnpaid++
case outcomeStopped:
stopped++
default:
expired++
}
if out.kind != outcomeSuccess && out.reason != "" {
reasons[out.reason]++
}
}
accounts := make([]types.Account, 0, len(accountProducts))
for name, commodityID := range accountProducts {
cookie, ok := s.AccountCookieByName(name)
if !ok {
continue
}
product := s.productForCommodityID(commodityID)
if product.CommodityID == "" {
product.CommodityID = commodityID
}
accounts = append(accounts, types.Account{Name: name, Cookie: cookie})
}
if len(accounts) == 0 {
logger.LogEvent("抢购", "warn", "固定次数抢购没有可执行账号")
return
}
lockReqs, payReqs, exchangeReqs := ctl.counts()
logger.LogEvent("抢购", "info",
"抢购任务结束: 成功=%d/%d,商品售罄=%d,被限流=%d,账号终止=%d,锁单未支付=%d,停止=%d,窗口结束=%d,耗时=%v",
success, len(outcomes), rejected, throttled, terminal, lockedUnpaid, stopped, expired, utils.RoundDuration(cost))
logger.LogEvent("抢购", "info", "抢购请求统计: 锁单=%d,支付=%d,直接兑换=%d", lockReqs, payReqs, exchangeReqs)
stopped := make(map[string]bool)
start := time.Now()
logger.LogEvent("抢购", "info", "固定次数抢购开始: %d 个账号,次数=%d,间隔=%dms", len(accounts), attempts, delayMs)
for round := 1; round <= attempts; round++ {
if s.runStopped() {
logger.LogEvent("抢购", "warn", "收到停止指令,固定次数抢购正在结束")
break
type reasonCount struct {
reason string
count int
}
ranked := make([]reasonCount, 0, len(reasons))
for reason, count := range reasons {
ranked = append(ranked, reasonCount{reason: reason, count: count})
}
sort.Slice(ranked, func(i, j int) bool {
if ranked[i].count != ranked[j].count {
return ranked[i].count > ranked[j].count
}
roundAttempts := make([]types.ExchangeAttempt, 0, len(accounts))
for _, account := range accounts {
if stopped[account.Name] {
continue
}
commodityID := accountProducts[account.Name]
product := s.productForCommodityID(commodityID)
if product.CommodityID == "" {
product.CommodityID = commodityID
}
roundAttempts = append(roundAttempts, types.ExchangeAttempt{Account: account, Product: product, Index: round})
}
if len(roundAttempts) == 0 {
break
}
if round > 1 && delayMs > 0 {
if s.interruptibleSleep(time.Duration(delayMs) * time.Millisecond) {
logger.LogEvent("抢购", "warn", "收到停止指令,固定次数抢购正在结束")
break
}
}
outcome := s.executeRound(roundAttempts, settings)
for name := range outcome.successAccounts {
stopped[name] = true
}
for name := range outcome.stoppedAccounts {
stopped[name] = true
}
logger.LogEvent("抢购", "info", "固定抢购第%d/%d轮完成: 成功=%d,剩余账号=%d", round, attempts, len(outcome.successAccounts), len(accounts)-len(stopped))
return ranked[i].reason < ranked[j].reason
})
for _, item := range ranked {
logger.LogEvent("抢购", "warn", "未成功原因: %s × %d 个账号", item.reason, item.count)
}
logger.LogEvent("抢购", "info", "固定次数抢购结束: 成功=%d/%d,耗时=%v", len(stopped), len(accounts), utils.RoundDuration(time.Since(start)))
}
// RunXiaodian 使用和平小店专用策略:固定次数、固定间隔、每轮直接调用 livebuy。
@@ -750,21 +844,6 @@ func normalizeXiaodianRun(attempts, delayMs, fallbackAttempts int) (int, time.Du
return attempts, time.Duration(delayMs) * time.Millisecond
}
// filterPendingAttempts 过滤掉已终止账号和已确认无库存的商品。
func (s *Scheduler) filterPendingAttempts(allAttempts []types.ExchangeAttempt, stoppedAccounts, stoppedProducts map[string]string) []types.ExchangeAttempt {
var pending []types.ExchangeAttempt
for _, attempt := range allAttempts {
if stoppedAccounts[attempt.Account.Name] != "" {
continue
}
if stoppedProducts[attempt.Product.CommodityID] != "" {
continue
}
pending = append(pending, attempt)
}
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
@@ -781,46 +860,6 @@ func filterCooldownAttempts(attempts []types.ExchangeAttempt, cooldownAccounts m
return out, nextReady
}
// pickRoundAttempts 每轮每个账号最多执行一次,避免同账号并发过猛触发频控。
func pickRoundAttempts(attempts []types.ExchangeAttempt, round, attemptsPerAccount int) []types.ExchangeAttempt {
if len(attempts) == 0 {
return nil
}
preferredIndex := 1
if attemptsPerAccount > 0 {
preferredIndex = ((round - 1) % attemptsPerAccount) + 1
}
byAccount := make(map[string]types.ExchangeAttempt)
fallback := make(map[string]types.ExchangeAttempt)
order := make([]string, 0, len(attempts))
for _, attempt := range attempts {
name := attempt.Account.Name
if _, ok := fallback[name]; !ok {
fallback[name] = attempt
order = append(order, name)
}
if attempt.Index == preferredIndex {
byAccount[name] = attempt
}
}
out := make([]types.ExchangeAttempt, 0, len(order))
for _, name := range order {
if attempt, ok := byAccount[name]; ok {
out = append(out, attempt)
} else {
out = append(out, fallback[name])
}
}
return out
}
// executeRound 执行一轮抢购,并返回成功和终止重试的账号。
func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt, settings runSettings) roundOutcome {
return s.executeRoundWithRunner(attempts, settings, nil)
}
func (s *Scheduler) executeXiaodianRound(attempts []types.ExchangeAttempt, settings runSettings) roundOutcome {
return s.executeRoundWithRunner(attempts, settings, s.runXiaodianAttempt)
}
@@ -858,23 +897,18 @@ func (s *Scheduler) executeRoundWithRunner(
return
}
var result types.ExchangeResult
if runner != nil {
result = runner(attempt)
} else if settings.seckillMode == types.SeckillModeAggressive {
result = s.runAttemptFast(attempt)
} else {
result = s.runAttempt(attempt)
}
result := runner(attempt)
key := fmt.Sprintf("%s_第%d包", result.Account, result.Attempt)
// 固定后缀:前端 useLogs/ControlStrip 按 /_第\d+包$/ 归并账号名。
// 用轮次做后缀时,抢购次数 >=10 会让前端按字典序取到中间某次的旧原因。
key := fmt.Sprintf("%s_第1包", result.Account)
s.setResult(key, result.Message)
if result.OK {
logger.LogAccountEvent("抢购", "success", result.Account, "成功: 账号=%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)
s.enqueueSuccessImage(attempt.Account, attempt.Product, result.RoleName)
} else {
logger.LogAccountEvent("抢购", "info", result.Account, "尝试: 账号=%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)
}
mu.Lock()
@@ -886,10 +920,7 @@ func (s *Scheduler) executeRoundWithRunner(
if cooldown := retryCooldownDuration(result.Message); cooldown > 0 {
outcome.cooldownAccounts[attempt.Account.Name] = time.Now().Add(jitterDuration(cooldown))
}
terminalAccount, terminalProduct, reason := classifyRetryStop(result.Message)
if runner != nil {
terminalAccount, terminalProduct, reason = classifyXiaodianRetryStop(result.Message)
}
terminalAccount, terminalProduct, reason := classifyXiaodianRetryStop(result.Message)
if terminalAccount {
outcome.stoppedAccounts[attempt.Account.Name] = reason
}
@@ -907,14 +938,6 @@ func (s *Scheduler) executeRoundWithRunner(
// ==================== 辅助函数 ====================
// modeName 返回抢购模式名称。
func modeName(mode types.SeckillMode) string {
if mode == types.SeckillModeAggressive {
return "激进"
}
return "标准"
}
// retryIntervalFor 根据配置的重试阶段计算当前应该使用的重试间隔。
func retryIntervalFor(retryStages []types.RetryStage, elapsed time.Duration) time.Duration {
elapsedSec := int(elapsed.Seconds())
@@ -931,11 +954,7 @@ func retryIntervalFor(retryStages []types.RetryStage, elapsed time.Duration) tim
}
func jitterDuration(base time.Duration) time.Duration {
if base <= 0 {
return 0
}
jitter := time.Duration(rand.Int63n(int64(base / 10)))
return base + jitter
return jitterFraction(base, 10)
}
func retryCooldownDuration(message string) time.Duration {
@@ -1018,35 +1037,25 @@ func dynamicAdvance(calibration types.TimeCalibration) time.Duration {
return advance
}
func uniqueAttemptAccounts(attempts []types.ExchangeAttempt) int {
seen := make(map[string]struct{}, len(attempts))
for _, attempt := range attempts {
seen[attempt.Account.Name] = struct{}{}
}
return len(seen)
}
func (s *Scheduler) buildAttempts(accountProducts map[string]string, attemptsPerAccount int) []types.ExchangeAttempt {
if attemptsPerAccount <= 0 {
attemptsPerAccount = constants.DefaultAttempts
}
// buildTasks 为每个账号生成一个抢购任务。
//
// 锁单+支付链路下,一次任务就是一次完整的"锁单→支付",不需要再按"N 个包"
// 为同一账号重复生成任务(历史实现会因此把预热缓存日志打两遍)。
func (s *Scheduler) buildTasks(accountProducts map[string]string) []types.ExchangeAttempt {
accounts := s.AccountSnapshot()
var attempts []types.ExchangeAttempt
tasks := make([]types.ExchangeAttempt, 0, len(accounts))
for _, account := range accounts {
commodityID := accountProducts[account.Name]
if commodityID == "" {
continue
}
product := s.productForCommodityID(commodityID)
for i := 1; i <= attemptsPerAccount; i++ {
attempts = append(attempts, types.ExchangeAttempt{
Account: account,
Product: product,
Index: i,
})
}
tasks = append(tasks, types.ExchangeAttempt{
Account: account,
Product: s.productForCommodityID(commodityID),
Index: 1,
})
}
return attempts
return tasks
}
func (s *Scheduler) productForCommodityID(commodityID string) types.Product {