- 精英手册兑换改为 createExchangeOrder 锁单后 payExchangeOrder 支付,不再查询商品状态与预兑 - 电竞手册保留直接兑换,标准模式重新取鉴权,激进模式复用鉴权 - csrfToken 优先复用 Cookie,校验失败自动刷新后重试一次 - 锁单支付按频控/通用退避表重试,临近过期不再重试 - 定时复校发现抢购已开始则不再改写触发时刻 - 升级 wails 至 v2.15.0
391 lines
12 KiB
Go
391 lines
12 KiB
Go
package seckill
|
||
|
||
import (
|
||
"errors"
|
||
"fmt"
|
||
"math/rand"
|
||
"strings"
|
||
"time"
|
||
|
||
"douyu_go/internal/client"
|
||
"douyu_go/internal/logger"
|
||
"douyu_go/internal/types"
|
||
"douyu_go/internal/utils"
|
||
)
|
||
|
||
var errPurchaseStopped = errors.New("已收到停止指令,锁单可能仍有效")
|
||
|
||
const (
|
||
peaceLockTTL = 300 * time.Second
|
||
peaceLockExpiryMargin = 15 * time.Second
|
||
peaceLockRetryFallback = 3 * time.Second
|
||
exchangeRateCooldown = 30 * time.Second
|
||
)
|
||
|
||
var (
|
||
peacePreLockMin = 300 * time.Millisecond
|
||
peacePreLockMax = 1200 * time.Millisecond
|
||
peaceLockPayMin = 2 * time.Second
|
||
peaceLockPayMax = 4 * time.Second
|
||
)
|
||
|
||
var peaceRateLimitBackoffs = []time.Duration{30 * time.Second, 60 * time.Second, 90 * time.Second}
|
||
var peaceGenericBackoffs = []time.Duration{2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second}
|
||
|
||
// runAttempt 按活动兑换。精英手册锁单后支付;电竞手册直接兑换。两者都不做商品预检。
|
||
func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
|
||
cli := s.clientSnapshot()
|
||
if cli.Activity.IsXiaodian {
|
||
return s.runXiaodianAttempt(attempt)
|
||
}
|
||
if !cli.Activity.UseCTN {
|
||
return s.runPeaceLockPay(attempt)
|
||
}
|
||
return s.runDirectExchange(attempt, false)
|
||
}
|
||
|
||
// runAttemptFast 激进模式。精英手册与标准模式相同;电竞手册复用鉴权后直接兑换。
|
||
func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.ExchangeResult {
|
||
cli := s.clientSnapshot()
|
||
if cli.Activity.IsXiaodian {
|
||
return s.runXiaodianAttempt(attempt)
|
||
}
|
||
if !cli.Activity.UseCTN {
|
||
return s.runPeaceLockPay(attempt)
|
||
}
|
||
return s.runDirectExchange(attempt, true)
|
||
}
|
||
|
||
func (s *Scheduler) runPeaceLockPay(attempt types.ExchangeAttempt) types.ExchangeResult {
|
||
cli := s.clientSnapshot()
|
||
result := types.ExchangeResult{
|
||
Account: attempt.Account.Name,
|
||
Product: attempt.Product.CommodityName,
|
||
Attempt: attempt.Index,
|
||
}
|
||
roleName, csrf := s.cachedAuth(attempt)
|
||
if csrf == "" {
|
||
var err error
|
||
csrf, err = cli.GenerateCSRF(attempt.Account.Cookie)
|
||
if err != nil {
|
||
result.Message = "失败|生成鉴权token失败: " + err.Error()
|
||
return result
|
||
}
|
||
}
|
||
|
||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "精英手册锁单支付: 账号=%s 商品=%s 第%d包", attempt.Account.Name, attempt.Product.CommodityName, attempt.Index)
|
||
if s.interruptibleSleep(randomSpan(peacePreLockMin, peacePreLockMax)) {
|
||
result.Message = "失败|已收到停止指令"
|
||
return result
|
||
}
|
||
|
||
locked, err := cli.CreateExchangeOrder(attempt.Account.Cookie, attempt.Product.CommodityID, 1, &csrf)
|
||
if err != nil {
|
||
delay := peaceLockRetryDelay(err.Error())
|
||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "锁定兑换商品失败(%s),%s 后重试一次", err.Error(), delay)
|
||
if s.interruptibleSleep(delay) {
|
||
result.Message = "失败|已收到停止指令"
|
||
return result
|
||
}
|
||
locked, err = cli.CreateExchangeOrder(attempt.Account.Cookie, attempt.Product.CommodityID, 1, &csrf)
|
||
if err != nil {
|
||
result.RoleName = roleName
|
||
result.Message = "失败|锁定兑换商品失败: " + err.Error()
|
||
return result
|
||
}
|
||
}
|
||
s.rememberAuth(attempt.Account.Name, csrf, roleName)
|
||
|
||
delay := randomSpan(peaceLockPayMin, peaceLockPayMax)
|
||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "锁单成功(订单 %s),%s 后支付", locked.OrderID, delay.Round(100*time.Millisecond))
|
||
if s.interruptibleSleep(delay) {
|
||
result.RoleName = roleName
|
||
result.Message = "失败|已收到停止指令,锁单可能仍有效"
|
||
return result
|
||
}
|
||
|
||
exchangeInfo, err := s.payLockedOrder(cli, attempt, locked, &csrf)
|
||
if err != nil {
|
||
result.RoleName = roleName
|
||
result.Message = "失败|" + err.Error()
|
||
return result
|
||
}
|
||
return s.finishExchange(cli, attempt, result, csrf, roleName, exchangeInfo)
|
||
}
|
||
|
||
func (s *Scheduler) payLockedOrder(cli *client.DouyuClient, attempt types.ExchangeAttempt, locked client.LockedExchangeOrder, csrf *string) (string, error) {
|
||
for try := 0; try < 6; try++ {
|
||
if s.runStopped() {
|
||
return "", errPurchaseStopped
|
||
}
|
||
info, err := cli.PayExchangeOrder(attempt.Account.Cookie, locked.OrderID, csrf)
|
||
if err == nil {
|
||
return info, nil
|
||
}
|
||
backoff, ok := peacePayBackoff(try, exchangeRateLimited(err.Error()))
|
||
if !ok {
|
||
if exchangeRateLimited(err.Error()) {
|
||
return "", errPayRateLimited(locked.OrderID, try, err)
|
||
}
|
||
return "", errPayFailed(locked.OrderID, try, err)
|
||
}
|
||
remaining := time.Until(locked.ExpiresAt)
|
||
if remaining <= 0 {
|
||
remaining = peaceLockTTL
|
||
}
|
||
if remaining-backoff < peaceLockExpiryMargin {
|
||
return "", errPayNearExpiry(locked.OrderID, remaining, err)
|
||
}
|
||
kind := "错误"
|
||
if exchangeRateLimited(err.Error()) {
|
||
kind = "频控"
|
||
}
|
||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "锁单 %s 支付%s退避 %s 后重试: %s", locked.OrderID, kind, backoff, err.Error())
|
||
if s.interruptibleSleep(backoff) {
|
||
return "", errPurchaseStopped
|
||
}
|
||
}
|
||
return "", errPayFailed(locked.OrderID, len(peaceGenericBackoffs), nil)
|
||
}
|
||
|
||
func (s *Scheduler) runDirectExchange(attempt types.ExchangeAttempt, reuseCache bool) types.ExchangeResult {
|
||
cli := s.clientSnapshot()
|
||
result := types.ExchangeResult{
|
||
Account: attempt.Account.Name,
|
||
Product: attempt.Product.CommodityName,
|
||
Attempt: attempt.Index,
|
||
}
|
||
roleName, csrf := s.cachedAuth(attempt)
|
||
if reuseCache {
|
||
cache := s.getAttemptCache(attempt.Account.Name)
|
||
if cache == nil || cache.CSRF == "" || time.Since(cache.LastCheck) >= qualifiedMaxAge {
|
||
return s.runDirectExchange(attempt, false)
|
||
}
|
||
csrf = cache.CSRF
|
||
if cache.RoleName != "" {
|
||
roleName = cache.RoleName
|
||
}
|
||
}
|
||
if csrf == "" {
|
||
var err error
|
||
csrf, err = cli.GenerateCSRF(attempt.Account.Cookie)
|
||
if err != nil {
|
||
result.Message = "失败|生成鉴权token失败: " + err.Error()
|
||
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, &csrf)
|
||
if err != nil {
|
||
s.rememberAuth(attempt.Account.Name, csrf, roleName)
|
||
errMsg := err.Error()
|
||
if reuseCache && shouldFallbackStandard(errMsg) {
|
||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "激进模式重新取鉴权后重试: 账号=%s 原因=%s", attempt.Account.Name, utils.TrimForLog(errMsg, 80))
|
||
s.setAttemptCache(attempt.Account.Name, nil)
|
||
return s.runDirectExchange(attempt, false)
|
||
}
|
||
result.RoleName = roleName
|
||
result.Message = "失败|" + errMsg
|
||
return result
|
||
}
|
||
return s.finishExchange(cli, attempt, result, csrf, roleName, exchangeInfo)
|
||
}
|
||
|
||
func (s *Scheduler) finishExchange(cli *client.DouyuClient, attempt types.ExchangeAttempt, result types.ExchangeResult, csrf, roleName, exchangeInfo string) types.ExchangeResult {
|
||
if roleName == "" {
|
||
name, err := cli.RoleName(attempt.Account.Cookie)
|
||
if err != nil {
|
||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||
} else {
|
||
roleName = name
|
||
}
|
||
}
|
||
s.rememberAuth(attempt.Account.Name, csrf, roleName)
|
||
result.OK = true
|
||
result.RoleName = roleName
|
||
if roleName != "" {
|
||
result.Message = "成功|" + roleName + "|" + exchangeInfo
|
||
} else {
|
||
result.Message = "成功|" + exchangeInfo
|
||
}
|
||
return result
|
||
}
|
||
|
||
func (s *Scheduler) cachedAuth(attempt types.ExchangeAttempt) (roleName, csrf string) {
|
||
if warmup, ok := s.warmupFor(attempt); ok {
|
||
roleName = warmup.RoleName
|
||
csrf = warmup.CSRF
|
||
}
|
||
if cache := s.getAttemptCache(attempt.Account.Name); cache != nil && cache.CSRF != "" && time.Since(cache.LastCheck) < qualifiedMaxAge {
|
||
if csrf == "" {
|
||
csrf = cache.CSRF
|
||
}
|
||
if roleName == "" {
|
||
roleName = cache.RoleName
|
||
}
|
||
}
|
||
return roleName, csrf
|
||
}
|
||
|
||
func (s *Scheduler) rememberAuth(accountName, csrf, roleName string) {
|
||
s.setAttemptCache(accountName, &types.AttemptCache{
|
||
CSRF: csrf,
|
||
RoleName: roleName,
|
||
Qualified: true,
|
||
LastCheck: time.Now(),
|
||
})
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
role, err := cli.XiaodianRole(attempt.Account.Cookie)
|
||
if err != nil {
|
||
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name,
|
||
"角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
|
||
}
|
||
roleName := role.RoleName
|
||
result.OK = true
|
||
result.RoleName = roleName
|
||
if roleName != "" {
|
||
result.Message = "成功|" + roleName + "|" + exchangeInfo
|
||
} else {
|
||
result.Message = "成功|" + exchangeInfo
|
||
}
|
||
return result
|
||
}
|
||
|
||
func peacePayBackoff(attempt int, rateLimited bool) (time.Duration, bool) {
|
||
table := peaceGenericBackoffs
|
||
if rateLimited {
|
||
table = peaceRateLimitBackoffs
|
||
}
|
||
if attempt < 0 || attempt >= len(table) {
|
||
return 0, false
|
||
}
|
||
return table[attempt], true
|
||
}
|
||
|
||
func peaceLockRetryDelay(message string) time.Duration {
|
||
if exchangeRateLimited(message) && len(peaceRateLimitBackoffs) > 0 {
|
||
return peaceRateLimitBackoffs[0]
|
||
}
|
||
return peaceLockRetryFallback
|
||
}
|
||
|
||
func exchangeRateLimited(message string) bool {
|
||
for _, hint := range []string{
|
||
"火爆", "频繁", "稍后", "太热", "限流", "繁忙", "人多", "排队", "手慢",
|
||
"用户行为异常", "点击太快", "请求过多", "请求太频繁", "频控",
|
||
} {
|
||
if strings.Contains(message, hint) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func randomSpan(min, max time.Duration) time.Duration {
|
||
if max <= min {
|
||
if min < 0 {
|
||
return 0
|
||
}
|
||
return min
|
||
}
|
||
return min + time.Duration(rand.Int63n(int64(max-min)+1))
|
||
}
|
||
|
||
func errPayRateLimited(orderID string, tries int, err error) error {
|
||
return fmt.Errorf("锁单 %s 支付被频控拦截(已退避重试%d次): %w", orderID, tries, err)
|
||
}
|
||
|
||
func errPayFailed(orderID string, tries int, err error) error {
|
||
if err == nil {
|
||
return fmt.Errorf("锁单 %s 支付失败(已重试%d次)", orderID, tries)
|
||
}
|
||
return fmt.Errorf("锁单 %s 支付失败(已重试%d次): %w", orderID, tries, err)
|
||
}
|
||
|
||
func errPayNearExpiry(orderID string, remaining time.Duration, err error) error {
|
||
return fmt.Errorf("锁单 %s 支付失败且临近过期(%ds): %w", orderID, int(remaining.Seconds()), err)
|
||
}
|
||
|
||
func shouldFallbackStandard(errMsg string) bool {
|
||
lower := strings.ToLower(errMsg)
|
||
switch {
|
||
case strings.Contains(lower, "csrf"):
|
||
return true
|
||
case strings.Contains(lower, "cvl_csrf_token"):
|
||
return true
|
||
case strings.Contains(lower, "preexchange"):
|
||
return true
|
||
case strings.Contains(lower, "limit"):
|
||
return true
|
||
case strings.Contains(errMsg, "预兑换"):
|
||
return true
|
||
case strings.Contains(errMsg, "限制检查"):
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
// ========== 激进模式缓存管理 ==========
|
||
|
||
func (s *Scheduler) getAttemptCache(accountName string) *types.AttemptCache {
|
||
s.attemptCacheMu.RLock()
|
||
defer s.attemptCacheMu.RUnlock()
|
||
return s.attemptCache[accountName]
|
||
}
|
||
|
||
// initCacheFromWarmup 从预热数据初始化激进模式缓存。
|
||
func (s *Scheduler) initCacheFromWarmup(attempts []types.ExchangeAttempt) {
|
||
for _, attempt := range attempts {
|
||
if warmup, ok := s.warmupFor(attempt); ok {
|
||
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
|
||
CSRF: warmup.CSRF,
|
||
RoleName: warmup.RoleName,
|
||
Qualified: warmup.Qualified,
|
||
LastCheck: time.Now(),
|
||
})
|
||
logger.LogAccountEvent("抢购", "info", attempt.Account.Name, "从预热初始化缓存: 账号=%s", attempt.Account.Name)
|
||
}
|
||
}
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
func (s *Scheduler) clearAttemptCache() {
|
||
s.attemptCacheMu.Lock()
|
||
defer s.attemptCacheMu.Unlock()
|
||
s.attemptCache = make(map[string]*types.AttemptCache)
|
||
}
|