重构: 活动热切换并发安全 + 代码清理优化

- 活动切换并发安全:App/Scheduler 增加 client/cfg 读写锁与快照访问,
  支持运行中热替换客户端,切换活动不再静默覆盖用户自定义 timeApiUrl
- 启动失败时写入崩溃日志文件便于事后排查
- 前端类型声明从 Wails 自动生成的绑定派生,避免手写契约漂移
- 提取 parseAccountFile 消除 ExportAccounts/OrganizeAccounts 重复解析逻辑
- 删除 utils 中未使用的 ReadJSON/WriteJSON/WriteError 及空目录 internal/app
- gofmt 统一格式化(activity/types/scheduler 字段对齐)
- 新增 logger/seckill/utils 单元测试
- 清理 git 中遗留产物(frontend/app.js、yml.txt、其他日志/)并补全 .gitignore
This commit is contained in:
yml2213
2026-07-29 12:33:16 +08:00
parent ed3fd5f09e
commit 3ae9cb4a42
20 changed files with 574 additions and 20390 deletions
+53 -15
View File
@@ -54,9 +54,10 @@ type runSettings struct {
// Scheduler 抢购调度器。
type Scheduler struct {
client *client.DouyuClient
paths types.AppPaths
font *truetype.Font
clientMu sync.RWMutex
client *client.DouyuClient
paths types.AppPaths
font *truetype.Font
successImages *image.SuccessImageSaver
@@ -82,8 +83,8 @@ type Scheduler struct {
resyncSchedule *time.Timer
warmupGen int64
warmupsMu sync.RWMutex
warmups map[string]types.WarmupData
warmupsMu sync.RWMutex
warmups map[string]types.WarmupData
warmupRunMu sync.Mutex
attemptCacheMu sync.RWMutex
@@ -128,6 +129,33 @@ func (s *Scheduler) Close() {
}
}
// clientSnapshot 返回当前 client 的指针快照(读锁保护,用于执行期间持有一个稳定引用)。
func (s *Scheduler) clientSnapshot() *client.DouyuClient {
s.clientMu.RLock()
defer s.clientMu.RUnlock()
return s.client
}
// UpdateClient 热替换底层 HTTP 客户端(用于活动切换)。
// 若有抢购任务正在运行则拒绝替换,返回 false。
func (s *Scheduler) UpdateClient(newClient *client.DouyuClient) bool {
s.runMu.Lock()
if s.running {
s.runMu.Unlock()
return false
}
s.runMu.Unlock()
s.clientMu.Lock()
defer s.clientMu.Unlock()
old := s.client
s.client = newClient
if old != nil && old.HTTPClient != nil {
old.HTTPClient.CloseIdleConnections()
}
return true
}
// UpdateProducts 更新商品缓存,抢购成功图片会优先使用中文商品名。
func (s *Scheduler) UpdateProducts(products []types.Product) {
next := make(map[string]types.Product, len(products))
@@ -817,6 +845,7 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
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 {
@@ -827,12 +856,12 @@ func (s *Scheduler) warmupAttempts(attempts []types.ExchangeAttempt) {
defer func() { <-limit }()
start := time.Now()
csrf, err := s.client.GenerateCSRF(attempt.Account.Cookie)
csrf, err := cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil {
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)
roleName, err := cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("预热", "warn", attempt.Account.Name, "角色预热失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -867,7 +896,8 @@ func uniqueWarmupAttempts(attempts []types.ExchangeAttempt) []types.ExchangeAtte
}
func (s *Scheduler) calibrateDouyuTime(label string) types.TimeCalibration {
calibration, err := s.client.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
cli := s.clientSnapshot()
calibration, err := cli.BestServerTimeCalibration(timeCalibrateRounds, timeCalibrateWait)
if err != nil {
logger.LogEvent("时间", "warn", "%s校准降级: %v", label, err)
}
@@ -906,6 +936,7 @@ func (s *Scheduler) stopSchedulesLocked() {
}
func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{
Account: attempt.Account.Name,
Product: attempt.Product.CommodityName,
@@ -922,7 +953,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
if csrf == "" {
var err error
csrf, err = s.client.GenerateCSRF(attempt.Account.Cookie)
csrf, err = cli.GenerateCSRF(attempt.Account.Cookie)
if err != nil {
result.Message = "失败|生成CSRF失败: " + err.Error()
return result
@@ -930,7 +961,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
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)
limit, err := cli.BatchExchangeLimit(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
result.Message = "失败|批量限制检查失败: " + err.Error()
return result
@@ -941,7 +972,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
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 {
if err := cli.PreExchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf); err != nil {
result.Message = "失败|预兑换失败: " + err.Error()
return result
}
@@ -953,7 +984,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 := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -967,7 +998,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
}
if roleName == "" {
roleName, err = s.client.RoleName(attempt.Account.Cookie)
roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -994,6 +1025,7 @@ func (s *Scheduler) runAttempt(attempt types.ExchangeAttempt) types.ExchangeResu
// runAttemptFast 激进模式的兑换逻辑,复用缓存的 CSRF,跳过 BatchExchangeLimit 和 PreExchange。
func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.ExchangeResult {
cli := s.clientSnapshot()
result := types.ExchangeResult{
Account: attempt.Account.Name,
Product: attempt.Product.CommodityName,
@@ -1014,7 +1046,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 := s.client.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
exchangeInfo, err := cli.Exchange(attempt.Account.Cookie, attempt.Product.CommodityID, &csrf)
if err != nil {
s.setAttemptCache(attempt.Account.Name, &types.AttemptCache{
CSRF: csrf,
@@ -1040,7 +1072,7 @@ func (s *Scheduler) runAttemptFast(attempt types.ExchangeAttempt) types.Exchange
}
if roleName == "" {
var err error
roleName, err = s.client.RoleName(attempt.Account.Cookie)
roleName, err = cli.RoleName(attempt.Account.Cookie)
if err != nil {
logger.LogAccountEvent("抢购", "warn", attempt.Account.Name, "角色名查询失败: 账号=%s err=%v", attempt.Account.Name, err)
}
@@ -1143,10 +1175,16 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (map[string]any, error
time.Now().Add(resyncRemain).In(constants.CST).Format("15:04:05.000"),
)
remainSecond := int(triggerTime.Sub(serverTime).Seconds())
if remainSecond < 0 {
remainSecond = 0
}
return map[string]any{
"success": true,
"targetTime": targetTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"triggerTime": triggerTime.In(constants.CST).Format("2006-01-02 15:04:05"),
"remainSecond": remainSecond,
"offsetMs": calibration.Offset.Milliseconds(),
"errorBoundMs": calibration.ErrorBound.Milliseconds(),
"rttMs": calibration.RTT.Milliseconds(),
+162
View File
@@ -0,0 +1,162 @@
package seckill
import (
"testing"
"time"
"douyu_go/internal/types"
)
func makeAttempts(names ...string) []types.ExchangeAttempt {
out := make([]types.ExchangeAttempt, 0, len(names))
for i, n := range names {
out = append(out, types.ExchangeAttempt{
Account: types.Account{Name: n},
Index: i + 1,
})
}
return out
}
func TestRetryIntervalFor(t *testing.T) {
stages := []types.RetryStage{
{MaxElapsed: 4, Interval: 120},
{MaxElapsed: 12, Interval: 200},
{MaxElapsed: 30, Interval: 500},
{MaxElapsed: 75, Interval: 1000},
}
cases := []struct {
elapsed time.Duration
want time.Duration
}{
{1 * time.Second, 120 * time.Millisecond},
{5 * time.Second, 200 * time.Millisecond},
{13 * time.Second, 500 * time.Millisecond},
{31 * time.Second, 1000 * time.Millisecond},
{100 * time.Second, 900 * time.Millisecond}, // 超出所有阶段,用默认值
}
for _, c := range cases {
if got := retryIntervalFor(stages, c.elapsed); got != c.want {
t.Errorf("retryIntervalFor(%v) = %v, want %v", c.elapsed, got, c.want)
}
}
}
func TestRetryIntervalForEmpty(t *testing.T) {
// 空阶段或无效阶段都回退到默认 900ms
if got := retryIntervalFor(nil, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(nil) = %v, want 900ms", got)
}
if got := retryIntervalFor([]types.RetryStage{{MaxElapsed: 0, Interval: 0}}, 1*time.Second); got != 900*time.Millisecond {
t.Errorf("retryIntervalFor(invalid) = %v, want 900ms", got)
}
}
func TestRetryCooldownDuration(t *testing.T) {
cases := []struct {
msg string
want time.Duration
}{
{"用户行为异常,请稍后再试", behaviorCooldown},
{"点击太快了", clickFastCooldown},
{"操作频繁请稍后", behaviorCooldown},
{"请求过多", behaviorCooldown},
{"请求太频繁", behaviorCooldown},
{"兑换成功", 0},
{"库存不足", 0},
}
for _, c := range cases {
if got := retryCooldownDuration(c.msg); got != c.want {
t.Errorf("retryCooldownDuration(%q) = %v, want %v", c.msg, got, c.want)
}
}
}
func TestClassifyRetryStop(t *testing.T) {
acc, prod, reason := classifyRetryStop("您已达本次活动兑换上限")
if !acc || prod || reason != "已达兑换上限" {
t.Errorf("classifyRetryStop(兑换上限) = (%v,%v,%q), want (true,false,'已达兑换上限')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("未绑定账号")
if !acc || prod || reason != "账号未绑定角色" {
t.Errorf("classifyRetryStop(未绑定) = (%v,%v,%q), want (true,false,'账号未绑定角色')", acc, prod, reason)
}
acc, prod, reason = classifyRetryStop("需要开通精英手册")
if !acc || prod || reason != "账号不满足精英手册条件" {
t.Errorf("classifyRetryStop(精英手册) = (%v,%v,%q), want (true,false,'账号不满足精英手册条件')", acc, prod, reason)
}
// 库存耗尽不停止
acc, prod, reason = classifyRetryStop("商品本次活动库存已耗完")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(库存耗完) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
// 普通错误不停止
acc, prod, reason = classifyRetryStop("网络超时")
if acc || prod || reason != "" {
t.Errorf("classifyRetryStop(普通错误) = (%v,%v,%q), want (false,false,'')", acc, prod, reason)
}
}
func TestFilterCooldownAttempts(t *testing.T) {
attempts := makeAttempts("a", "b", "c")
now := time.Now()
cooldown := map[string]time.Time{
"a": now.Add(5 * time.Second), // 仍在冷却
"b": now.Add(-5 * time.Second), // 已过期
}
out, nextReady := filterCooldownAttempts(attempts, cooldown, now)
if len(out) != 2 {
t.Fatalf("filterCooldownAttempts out length = %d, want 2", len(out))
}
for _, a := range out {
if a.Account.Name == "a" {
t.Errorf("account 'a' should be filtered out")
}
}
if nextReady.IsZero() {
t.Errorf("nextReady should not be zero")
}
if !nextReady.After(now) {
t.Errorf("nextReady should be after now")
}
}
func TestPickRoundAttempts(t *testing.T) {
// 账号 A 有 3 个包,账号 B 有 3 个包
attempts := []types.ExchangeAttempt{
{Account: types.Account{Name: "A"}, Index: 1},
{Account: types.Account{Name: "A"}, Index: 2},
{Account: types.Account{Name: "A"}, Index: 3},
{Account: types.Account{Name: "B"}, Index: 1},
{Account: types.Account{Name: "B"}, Index: 2},
{Account: types.Account{Name: "B"}, Index: 3},
}
// 第 1 轮每账号选第 1 包
out := pickRoundAttempts(attempts, 1, 3)
if len(out) != 2 {
t.Fatalf("pickRoundAttempts round1 length = %d, want 2", len(out))
}
for _, a := range out {
if a.Index != 1 {
t.Errorf("round1 should pick index 1, got %d for %s", a.Index, a.Account.Name)
}
}
// 第 2 轮每账号选第 2 包
out = pickRoundAttempts(attempts, 2, 3)
for _, a := range out {
if a.Index != 2 {
t.Errorf("round2 should pick index 2, got %d for %s", a.Index, a.Account.Name)
}
}
// attemptsPerAccount=0 时回退取各自首个
out = pickRoundAttempts(attempts, 1, 0)
for _, a := range out {
if a.Index != 1 {
t.Errorf("round with 0 perAccount should pick index 1, got %d", a.Index)
}
}
// 空输入
if out := pickRoundAttempts(nil, 1, 3); out != nil {
t.Errorf("pickRoundAttempts(nil) = %v, want nil", out)
}
}