feat: improve xiaodian seckill flow

This commit is contained in:
yml2213
2026-08-08 23:04:40 +08:00
parent 16972b41cd
commit dde2b43d82
19 changed files with 871 additions and 64 deletions
+40 -2
View File
@@ -59,7 +59,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
})
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "资格预检通过: 账号=%s 商品=%s,后续可直兑", attempt.Account.Name, attempt.Product.CommodityName)
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.ExchangeProduct(attempt.Account.Cookie, attempt.Product, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -121,7 +121,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "激进模式直兑: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
// 直接调用 Exchange
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.ExchangeProduct(attempt.Account.Cookie, attempt.Product, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -169,6 +169,44 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
return result
}
// runXiaodianAttempt 和平小店专用兑换:跳过手册鉴权、批量限制和预兑换,直接调用 livebuy。
func (s *Scheduler) runXiaodianAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{
Account: attempt.Account.Name,
Product: attempt.Product.CommodityName,
Attempt: attempt.Index,
}
if s.runStopped() {
result.Message = "失败|已收到停止指令"
return result
}
logger.LogAccountEvent("抢购", "info", attempt.Account.Name,
"和平小店直接兑换: 账号=%s 商品=%s 第%d次",
attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
exchangeInfo, err := cli.ExchangeProduct(attempt.Account.Cookie, attempt.Product, nil)
if err != nil {
result.Message = "失败|" + err.Error()
return result
}
roleName, err := cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name,
"角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
}
result.OK = true
result.RoleName = roleName
if roleName != "" {
result.Message = "成功|" + roleName + "|" + exchangeInfo
} else {
result.Message = "成功|" + exchangeInfo
}
return result
}
func shouldFallbackStandard(errMsg string) bool {
lower := strings.ToLower(errMsg)
switch {
+10 -3
View File
@@ -42,7 +42,7 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
s.clearWarmups()
s.scheduleMu.Unlock()
s.scheduleTimers(ap, targetTime, triggerTime, calibration, false)
s.scheduleTimers(ap, targetTime, triggerTime, calibration, req.Attempts, req.DelayMs, false)
resyncRemain := triggerTime.Sub(serverTime) - resyncBeforeTrigger
if resyncRemain < 0 {
@@ -52,7 +52,7 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
s.scheduleMu.Lock()
s.replaceTimerLocked(&s.resyncSchedule, resyncRemain, func() {
newCalibration := s.calibrateDouyuTime("临近")
s.scheduleTimers(ap, targetTime, triggerTime, newCalibration, true)
s.scheduleTimers(ap, targetTime, triggerTime, newCalibration, req.Attempts, req.DelayMs, true)
})
s.scheduleMu.Unlock()
@@ -89,7 +89,7 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
}, nil
}
func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime, triggerTime time.Time, calibration types.TimeCalibration, resync bool) {
func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime, triggerTime time.Time, calibration types.TimeCalibration, attempts, delayMs int, resync bool) {
serverTime := calibration.EstimatedServerNow()
remain := triggerTime.Sub(serverTime)
if remain < 0 {
@@ -107,6 +107,9 @@ func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime
if atomic.LoadInt64(&s.warmupGen) != gen {
return
}
if s.clientSnapshot().Activity.IsXiaodian {
return
}
logger.LogEvent("预热", "success", "预热触发: 本地=%s", time.Now().In(constants.CST).Format("15:04:05.000"))
settings := s.settingsSnapshot()
attempts := s.buildAttempts(accountProducts, settings.attempts)
@@ -124,6 +127,10 @@ func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime
logger.LogEvent("抢购", "warn", "已有抢购任务正在运行,本次定时触发已跳过")
return
}
if s.clientSnapshot().Activity.IsXiaodian {
s.RunXiaodian(accountProducts, attempts, delayMs)
return
}
s.RunNow(accountProducts)
})
if resync {
+259 -19
View File
@@ -18,17 +18,18 @@ 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 = 5 * time.Second
clickFastCooldown = 3 * time.Second
internalAdvance = 50 * time.Millisecond
maxCooldownCount = 5
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 = 5 * time.Second
clickFastCooldown = 3 * time.Second
internalAdvance = 50 * time.Millisecond
maxCooldownCount = 5
xiaodianDefaultDelay = 500 * time.Millisecond
)
type roundOutcome struct {
@@ -69,8 +70,12 @@ type Scheduler struct {
resultsMu sync.RWMutex
results map[string]string
runMu sync.Mutex
running bool
runMu sync.Mutex
running bool
stopRun chan struct{}
stopRequested bool
stateMu sync.RWMutex
onStateChange func(string)
// pendingClient 保存运行中收到的客户端更新,当前任务结束后自动应用。
pendingClient *client.DouyuClient
@@ -91,6 +96,22 @@ type Scheduler struct {
products map[string]types.Product
}
// SetStateChangeCallback 设置运行状态变化回调。
func (s *Scheduler) SetStateChangeCallback(cb func(string)) {
s.stateMu.Lock()
s.onStateChange = cb
s.stateMu.Unlock()
}
func (s *Scheduler) emitState(state string) {
s.stateMu.RLock()
cb := s.onStateChange
s.stateMu.RUnlock()
if cb != nil {
cb(state)
}
}
// New 创建抢购调度器。
func New(cli *client.DouyuClient, paths types.AppPaths, font *truetype.Font, concurrency, attempts int, retryStages []types.RetryStage, seckillMode types.SeckillMode) *Scheduler {
if concurrency <= 0 {
@@ -289,17 +310,23 @@ func (s *Scheduler) setResult(key, value string) {
// TryStartRun 尝试开始抢购,返回 false 表示已有任务在运行。
func (s *Scheduler) TryStartRun() bool {
s.runMu.Lock()
defer s.runMu.Unlock()
if s.running {
s.runMu.Unlock()
return false
}
s.running = true
s.stopRequested = false
s.stopRun = make(chan struct{})
s.runMu.Unlock()
s.emitState("running")
return true
}
func (s *Scheduler) finishRun() {
s.runMu.Lock()
s.running = false
s.stopRequested = false
s.stopRun = nil
pendingClient := s.pendingClient
s.pendingClient = nil
s.runMu.Unlock()
@@ -308,6 +335,59 @@ func (s *Scheduler) finishRun() {
s.replaceClient(pendingClient)
logger.LogEvent("配置", "success", "抢购任务结束,已应用等待中的客户端配置")
}
s.emitState("idle")
}
// StopRun 请求停止当前正在执行的抢购任务。
func (s *Scheduler) StopRun() bool {
s.runMu.Lock()
if !s.running || s.stopRequested || s.stopRun == nil {
s.runMu.Unlock()
return false
}
s.stopRequested = true
close(s.stopRun)
s.runMu.Unlock()
s.emitState("stopping")
return true
}
// IsRunning 返回当前是否有抢购任务正在执行。
func (s *Scheduler) IsRunning() bool {
s.runMu.Lock()
defer s.runMu.Unlock()
return s.running
}
func (s *Scheduler) stopRunChan() <-chan struct{} {
s.runMu.Lock()
defer s.runMu.Unlock()
return s.stopRun
}
func (s *Scheduler) runStopped() bool {
s.runMu.Lock()
defer s.runMu.Unlock()
return s.stopRequested
}
func (s *Scheduler) interruptibleSleep(d time.Duration) bool {
if d <= 0 {
return s.runStopped()
}
stop := s.stopRunChan()
if stop == nil {
time.Sleep(d)
return false
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return false
case <-stop:
return true
}
}
// RunNow 立即执行抢购任务,持续循环直到超时或全部成功。
@@ -340,6 +420,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
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)
@@ -373,7 +457,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
}
if sleepFor > 0 {
logger.LogEvent("抢购", "info", "第%d轮账号冷却中,等待=%v", round, utils.RoundDuration(sleepFor))
time.Sleep(sleepFor)
if s.interruptibleSleep(sleepFor) {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
}
continue
}
@@ -414,6 +501,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
}
}
if s.runStopped() {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
if len(outcome.successAccounts) > 0 {
logger.LogEvent("抢购", "success", "第%d轮成功: %d 个账号", round, len(outcome.successAccounts))
}
@@ -424,7 +515,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
retryInterval := retryIntervalFor(settings.retryStages, time.Since(startTime))
if retryInterval > 0 && time.Since(startTime)+retryInterval < seckillMaxDuration {
time.Sleep(jitterDuration(retryInterval))
if s.interruptibleSleep(jitterDuration(retryInterval)) {
logger.LogEvent("抢购", "warn", "收到停止指令,抢购任务正在结束")
break
}
}
}
@@ -471,6 +565,10 @@ func (s *Scheduler) RunFixed(accountProducts map[string]string, attempts, delayM
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
}
roundAttempts := make([]types.ExchangeAttempt, 0, len(accounts))
for _, account := range accounts {
if stopped[account.Name] {
@@ -487,7 +585,10 @@ func (s *Scheduler) RunFixed(accountProducts map[string]string, attempts, delayM
break
}
if round > 1 && delayMs > 0 {
time.Sleep(time.Duration(delayMs) * time.Millisecond)
if s.interruptibleSleep(time.Duration(delayMs) * time.Millisecond) {
logger.LogEvent("抢购", "warn", "收到停止指令,固定次数抢购正在结束")
break
}
}
outcome := s.executeRound(roundAttempts, settings)
for name := range outcome.successAccounts {
@@ -501,6 +602,103 @@ func (s *Scheduler) RunFixed(accountProducts map[string]string, attempts, delayM
logger.LogEvent("抢购", "info", "固定次数抢购结束: 成功=%d/%d,耗时=%v", len(stopped), len(accounts), utils.RoundDuration(time.Since(start)))
}
// RunXiaodian 使用和平小店专用策略:固定次数、固定间隔、每轮直接调用 livebuy。
// 小店补货不依赖旧活动的 75 秒阶段窗口,也不执行手册的预检链路。
func (s *Scheduler) RunXiaodian(accountProducts map[string]string, attempts, delayMs int) {
defer s.finishRun()
s.ClearResults()
settings := s.settingsSnapshot()
attempts, delay := normalizeXiaodianRun(attempts, delayMs, settings.attempts)
accounts := make([]types.Account, 0, len(accountProducts))
for name := range accountProducts {
cookie, ok := s.AccountCookieByName(name)
if !ok {
continue
}
accounts = append(accounts, types.Account{Name: name, Cookie: cookie})
}
if len(accounts) == 0 {
logger.LogEvent("抢购", "warn", "和平小店抢购没有可执行账号")
return
}
stopped := make(map[string]bool)
start := time.Now()
logger.LogEvent("抢购", "info", "和平小店抢购开始: %d 个账号,次数=%d,间隔=%dms",
len(accounts), attempts, delay.Milliseconds())
for round := 1; round <= attempts; round++ {
if s.runStopped() {
logger.LogEvent("抢购", "warn", "收到停止指令,和平小店抢购正在结束")
break
}
if round > 1 && s.interruptibleSleep(delay) {
logger.LogEvent("抢购", "warn", "收到停止指令,和平小店抢购正在结束")
break
}
roundAttempts := make([]types.ExchangeAttempt, 0, len(accounts))
for _, account := range accounts {
if stopped[account.Name] {
continue
}
productID := accountProducts[account.Name]
product := s.productForCommodityID(productID)
if product.CommodityID == "" {
product.CommodityID = productID
}
roundAttempts = append(roundAttempts, types.ExchangeAttempt{
Account: account,
Product: product,
Index: round,
})
}
if len(roundAttempts) == 0 {
break
}
outcome := s.executeXiaodianRound(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,剩余账号=%d",
round, attempts, len(outcome.successAccounts), len(outcome.stoppedAccounts), len(accounts)-len(stopped))
if len(stopped) >= len(accounts) {
break
}
}
logger.LogEvent("抢购", "info", "和平小店抢购结束: 成功或停止=%d/%d,耗时=%v",
len(stopped), len(accounts), utils.RoundDuration(time.Since(start)))
}
func normalizeXiaodianRun(attempts, delayMs, fallbackAttempts int) (int, time.Duration) {
if attempts <= 0 {
attempts = fallbackAttempts
}
if attempts <= 0 {
attempts = 3
}
if attempts > 100000 {
attempts = 100000
}
if delayMs < 0 {
delayMs = 0
}
if delayMs == 0 {
delayMs = int(xiaodianDefaultDelay / time.Millisecond)
}
if delayMs > 60000 {
delayMs = 60000
}
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
@@ -569,6 +767,18 @@ func pickRoundAttempts(attempts []types.ExchangeAttempt, round, attemptsPerAccou
// 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)
}
func (s *Scheduler) executeRoundWithRunner(
attempts []types.ExchangeAttempt,
settings runSettings,
runner func(types.ExchangeAttempt) types.ExchangeResult,
) roundOutcome {
outcome := roundOutcome{
successAccounts: make(map[string]bool),
stoppedAccounts: make(map[string]string),
@@ -581,15 +791,25 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt, settings runS
var wg sync.WaitGroup
for _, attempt := range attempts {
if s.runStopped() {
break
}
wg.Add(1)
go func(attempt types.ExchangeAttempt) {
defer wg.Done()
if s.runStopped() {
return
}
limit <- struct{}{}
defer func() { <-limit }()
if s.runStopped() {
return
}
// 根据模式选择执行方法
var result types.ExchangeResult
if settings.seckillMode == types.SeckillModeAggressive {
if runner != nil {
result = runner(attempt)
} else if settings.seckillMode == types.SeckillModeAggressive {
result = s.runAttemptFast(attempt)
} else {
result = s.runAttempt(attempt)
@@ -614,6 +834,9 @@ func (s *Scheduler) executeRound(attempts []types.ExchangeAttempt, settings runS
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)
}
if terminalAccount {
outcome.stoppedAccounts[attempt.Account.Name] = reason
}
@@ -695,6 +918,23 @@ func classifyRetryStop(message string) (account bool, product bool, reason strin
}
}
func classifyXiaodianRetryStop(message string) (account bool, product bool, reason string) {
switch {
case strings.Contains(message, "已达限量"),
strings.Contains(message, "已达本次活动兑换上限"),
strings.Contains(message, "兑换上限"):
return true, false, "已达兑换限量"
case strings.Contains(message, "未绑定账号"):
return true, false, "账号未绑定角色"
case strings.Contains(message, "商品不存在"),
strings.Contains(message, "商品已下架"),
strings.Contains(message, "不支持该商品"):
return false, true, "商品不可兑换"
default:
return false, false, ""
}
}
func uniqueAttemptAccounts(attempts []types.ExchangeAttempt) int {
seen := make(map[string]struct{}, len(attempts))
for _, attempt := range attempts {
+15
View File
@@ -52,6 +52,21 @@ func TestRetryIntervalForEmpty(t *testing.T) {
}
}
func TestNormalizeXiaodianRun(t *testing.T) {
attempts, delay := normalizeXiaodianRun(0, 0, 4)
if attempts != 4 || delay != xiaodianDefaultDelay {
t.Fatalf("normalizeXiaodianRun fallback = (%d,%v), want (4,%v)", attempts, delay, xiaodianDefaultDelay)
}
attempts, delay = normalizeXiaodianRun(100001, 70000, 0)
if attempts != 100000 || delay != 60*time.Second {
t.Fatalf("normalizeXiaodianRun clamp = (%d,%v), want (100000,60s)", attempts, delay)
}
attempts, delay = normalizeXiaodianRun(2, 150, 0)
if attempts != 2 || delay != 150*time.Millisecond {
t.Fatalf("normalizeXiaodianRun explicit = (%d,%v), want (2,150ms)", attempts, delay)
}
}
func TestRetryCooldownDuration(t *testing.T) {
cases := []struct {
msg string