package seckill import ( "fmt" "sync" "time" "douyu_go/internal/logger" "douyu_go/internal/types" "douyu_go/internal/utils" ) func warmupKey(attempt types.ExchangeAttempt) string { return fmt.Sprintf("%s|%s", attempt.Account.Name, attempt.Product.CommodityID) } func (s *Scheduler) setWarmup(key string, data types.WarmupData) { s.warmupsMu.Lock() defer s.warmupsMu.Unlock() if s.warmups == nil { s.warmups = make(map[string]types.WarmupData) } s.warmups[key] = data } func (s *Scheduler) warmupFor(attempt types.ExchangeAttempt) (types.WarmupData, bool) { s.warmupsMu.RLock() data, ok := s.warmups[warmupKey(attempt)] s.warmupsMu.RUnlock() if !ok || data.CreatedAt.IsZero() || time.Since(data.CreatedAt) > warmupMaxAge { return types.WarmupData{}, false } return data, true } func (s *Scheduler) clearWarmups() { s.warmupsMu.Lock() defer s.warmupsMu.Unlock() s.warmups = make(map[string]types.WarmupData) } func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) { s.warmupRunMu.Lock() defer s.warmupRunMu.Unlock() attempts = uniqueWarmupAttempts(attempts) if len(attempts) == 0 { return } s.clearWarmups() 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 { wg.Add(1) go func(attempt types.ExchangeAttempt) { defer wg.Done() limit <- struct{}{} defer func() { <-limit }() start := time.Now() csrf, err := cli.GenerateCSRF(attempt.Account.Cookie) if err != nil { logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "鉴权token预热失败: 账号=%s 商品=%s err=%v", attempt.Account.Name, attempt.Product.CommodityName, err) return } roleName, err := cli.RoleName(attempt.Account.Cookie) if err != nil { logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err) } s.setWarmup(warmupKey(attempt), types.WarmupData{ CSRF: csrf, RoleName: roleName, Qualified: true, CreatedAt: time.Now(), }) logger.LogAccountEvent("预热", "success", attempt.Account.Name, "预热完成: 账号=%s 商品=%s 耗时=%s", attempt.Account.Name, attempt.Product.CommodityName, utils.RoundDuration(time.Since(start))) }(attempt) } wg.Wait() logger.LogEvent("预热", "info", "预热任务结束") } func uniqueWarmupAttempts(attempts []types.ExchangeAttempt) []types.ExchangeAttempt { if len(attempts) <= 1 { return attempts } seen := make(map[string]struct{}, len(attempts)) out := make([]types.ExchangeAttempt, 0, len(attempts)) for _, attempt := range attempts { key := warmupKey(attempt) if _, ok := seen[key]; ok { continue } seen[key] = struct{}{} out = append(out, attempt) } return out }