refactor(sniper): 对齐 dygou_go 调度架构,增加双时间日志并解耦预热

- 抢购调度重构:参考 dygou_go 将 sniper 拆分为独立子模块(runner/run_control/retry/exchange/classify/config/summary/category/helpers);移除全局自适应降速与轮次上限,采用账号独立循环、统一账号级退避、单请求并发闸门与首发错峰
- 预热与建连优化:默认关闭预热(避免单账号超时连坐整机开抢),开启时转为后台非阻塞协程;WebSocket 握手超时从 10s 降至 1500ms
- 双时间日志:logger 增加 SetServerOffset,校准后日志前缀自动渲染「本地时间(H虎牙估算时间)」,实现跨机器绝对毫秒对齐
- 默认配置调优:版本提升至 v0.5.0,默认线程调为 2(缓解多实例并发限流),前端自动平滑迁移
- 验证方式:go test ./... -count=1 全通,npm run build 构建正常,单测覆盖双时间与预热配置
This commit is contained in:
yml2213
2026-10-17 18:29:17 +08:00
parent 2451466bed
commit 6e5beac151
21 changed files with 2142 additions and 2078 deletions
+125 -92
View File
@@ -98,39 +98,61 @@ func TestRetryEscalationMath(t *testing.T) {
t.Fatalf("stageMultiplier(%v)=%d, want %d", elapsed, got, want)
}
}
// 正常等待类(售罄/未开放)放慢得更保守,避免错过库存回流。
if got := stageMultiplier(6*time.Second, CategorySoldOut); got != 2 {
t.Fatalf("售罄阶段倍率=%d, want 2", got)
// 售罄也按同一账号级退避阶梯放慢,避免每轮固定高速探测。
if got := stageMultiplier(6*time.Second, CategorySoldOut); got != 3 {
t.Fatalf("售罄阶段倍率=%d, want 3", got)
}
}
// TestThrottleGovernorEscalatesAndRecovers 验证全局降速器:连续无进展才降速、有进展立刻回退。
func TestThrottleGovernorEscalatesAndRecovers(t *testing.T) {
g := newThrottleGovernor()
g.minRequests = 2
g.stallWindow = time.Millisecond
g.lastProgress = time.Now().Add(-time.Second)
g.lastEscalate = time.Now().Add(-time.Second)
g.observe(CategoryTooFrequent)
if got := g.current(); got != 1 {
t.Fatalf("未达阈值不该降速,factor=%v", got)
}
g.observe(CategoryTooFrequent)
if got := g.current(); got <= 1 {
t.Fatalf("连续无进展应开始降速,factor=%v", got)
}
if got := g.peak(); got <= 1 {
t.Fatalf("peak 应记录最大倍率,实际 %v", got)
// TestCompleteRoundSessionStreakIsScopedToAccount 验证会话失效计数只属于当前账号,
// 网络/协议错误不会洗掉计数,任意可信业务回包才会清零。
func TestCompleteRoundSessionStreakIsScopedToAccount(t *testing.T) {
state := newRunState([]Account{{UID: 1}, {UID: 2}}, 1, 1, Config{})
state.completeRound(1, []string{CategorySessionLost}, defaultSessionLostLimit)
state.completeRound(1, []string{CategorySessionLost}, defaultSessionLostLimit)
if got := state.accounts[1].sessionStreak; got != 2 {
t.Fatalf("sessionStreak=%d, want 2", got)
}
before := g.current()
g.observe(CategorySuccess)
if got := g.current(); got >= before {
t.Fatalf("有进展后应回退,factor 从 %v 到 %v", before, got)
state.completeRound(2, []string{CategorySoldOut}, defaultSessionLostLimit)
if got := state.accounts[1].sessionStreak; got != 2 {
t.Fatalf("其他账号不应重置会话失效计数,got=%d", got)
}
if got := g.current(); got < 1 {
t.Fatalf("倍率不应小于 1,实际 %v", got)
state.completeRound(1, []string{CategoryError}, defaultSessionLostLimit)
state.completeRound(1, []string{CategoryProtocol}, defaultSessionLostLimit)
if got := state.accounts[1].sessionStreak; got != 2 {
t.Fatalf("网络/协议错误不应重置会话失效计数,got=%d", got)
}
state.completeRound(1, []string{CategorySoldOut}, defaultSessionLostLimit)
if got := state.accounts[1].sessionStreak; got != 0 {
t.Fatalf("可信业务回包后应清零,got=%d", got)
}
}
// TestCompleteRoundCountsEachRoundOnce 验证多目标同一轮失败只增加一次连续失败,
// 不会因为 target 多而把退避倍率放大两次。
func TestCompleteRoundCountsEachRoundOnce(t *testing.T) {
state := newRunState([]Account{{UID: 1}}, 2, 1, Config{})
state.completeRound(1, []string{CategoryTooFrequent, CategorySessionLost}, defaultSessionLostLimit)
if got := state.accounts[1].failStreak; got != 1 {
t.Fatalf("failStreak=%d, want 1(每轮只计一次)", got)
}
if got := state.accounts[1].sessionStreak; got != 1 {
t.Fatalf("sessionStreak=%d, want 1", got)
}
state.completeRound(1, []string{CategorySuccess}, defaultSessionLostLimit)
if got := state.accounts[1].failStreak; got != 0 {
t.Fatalf("成功后 failStreak 应清零,got=%d", got)
}
}
// TestDefaultSessionLostLimitToleratesTransientBurst 验证未显式配置时,不会因为
// 洪峰中常见的 3 次瞬时 session_lost 就把有效账号整场踢出。
func TestDefaultSessionLostLimitToleratesTransientBurst(t *testing.T) {
if got := sessionLostLimit(Config{}); got <= 3 {
t.Fatalf("默认会话失效阈值=%d,want > 3(避免瞬时洪峰误停账号)", got)
}
}
@@ -193,39 +215,42 @@ func TestRunStateFirstWaveStagger(t *testing.T) {
}
}
// TestRunStateSessionStreakResetIsScopedAndIndependentOfGovernor 验证会话失效计数
// 只按当前账号清理,并且不依赖自适应降速开关。
func TestRunStateSessionStreakResetIsScopedAndIndependentOfGovernor(t *testing.T) {
for _, withGovernor := range []bool{false, true} {
state := newRunState([]Account{{UID: 1}, {UID: 2}}, 1, 1, Config{})
if withGovernor {
state.governor = newThrottleGovernor()
}
state.bumpSessionStreak(1, 0)
state.bumpSessionStreak(1, 0)
// 另一个账号拿到正常业务响应,不能重置账号 1 的连续失效计数。
state.observeThrottle(2, CategorySoldOut)
if got := state.accounts[1][0].SessionStreak; got != 2 {
t.Fatalf("governor=%v: 其他账号不应重置会话失效计数,got=%d", withGovernor, got)
}
// 网络错误 / 协议异常没有可信业务响应,也不能把失效计数洗掉。
state.observeThrottle(1, CategoryError)
state.observeThrottle(1, CategoryProtocol)
if got := state.accounts[1][0].SessionStreak; got != 2 {
t.Fatalf("governor=%v: 网络/协议错误不应重置会话失效计数,got=%d", withGovernor, got)
}
// 账号 1 自己拿到正常业务响应后必须清零,即使降速器关闭。
state.observeThrottle(1, CategorySoldOut)
if got := state.accounts[1][0].SessionStreak; got != 0 {
t.Fatalf("governor=%v: 本账号恢复后应清零,got=%d", withGovernor, got)
}
// TestRunTargetsThrottleOnOneTargetDoesNotSkipAnother 验证账号级退避不会让
// 一个 target 的限流结果阻塞同一轮里的另一个 target。这是 per-target 重试
// 状态被移除后的核心行为。
func TestRunTargetsThrottleOnOneTargetDoesNotSkipAnother(t *testing.T) {
var secondSucceeded atomic.Bool
client := &fakeActivityClient{
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
if pid == 1 {
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
}
secondSucceeded.Store(true)
return &huya.ScoreExchangePrizeResp{Status: 200, Msg: "请求成功", OrderID: "O1"}, nil
},
}
runner := Runner{Client: client}
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
{PID: 1},
{PID: 2},
}, Config{
SID: 2203,
maxAttempts: 1,
Delay: time.Millisecond,
DirectExchange: true,
StopAccountAfterSuccess: true,
}, nil)
if err != nil {
t.Fatal(err)
}
if _, count, _ := client.counts(); count != 2 {
t.Fatalf("exchangeCount=%d, want 2(同一轮两个目标都要尝试)", count)
}
if !secondSucceeded.Load() {
t.Fatal("第二个目标应成功")
}
}
// TestRunTargetsWaitsForWindowWithoutPrefire 验证即使不需要预打,也不会提前进入窗口循环。
func TestRunTargetsWaitsForWindowWithoutPrefire(t *testing.T) {
var mu sync.Mutex
var first time.Time
@@ -244,7 +269,7 @@ func TestRunTargetsWaitsForWindowWithoutPrefire(t *testing.T) {
SID: 2203,
OpenAt: openAt,
windowOverride: 20 * time.Millisecond,
Loops: 1,
maxAttempts: 1,
Delay: time.Millisecond,
StartAhead: 100 * time.Millisecond,
ErrorBackoff: time.Millisecond,
@@ -272,7 +297,7 @@ func TestRunTargetsStopAccountAfterSuccessStopsAllTargets(t *testing.T) {
{PID: 2},
}, Config{
SID: 2203,
Loops: 2,
maxAttempts: 2,
Delay: time.Millisecond,
StopAccountAfterSuccess: true,
}, nil)
@@ -298,7 +323,7 @@ func TestRunTargetsSessionLostStopsWholeAccount(t *testing.T) {
{PID: 2},
}, Config{
SID: 2203,
Loops: 10,
maxAttempts: 10,
Delay: 5 * time.Millisecond,
ErrorBackoff: time.Millisecond,
SessionLostLimit: 3,
@@ -306,9 +331,10 @@ func TestRunTargetsSessionLostStopsWholeAccount(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// 第 1、2 轮各打两个目标;第 3 轮第一个目标连续第 3 次失效后整账号停止。
if _, exchangeCount, _ := client.counts(); exchangeCount != 5 {
t.Fatalf("exchangeCount=%d, want 5(达到阈值后应停止整个账号)", exchangeCount)
// 每轮会尝试两个目标;第 1 轮 2 次、第 2 轮 2 次、第 3 轮两个目标都返回
// session_lost 后账号级计数达到 3,共 6 次请求。
if _, exchangeCount, _ := client.counts(); exchangeCount != 6 {
t.Fatalf("exchangeCount=%d, want 6(达到阈值后应停止整个账号)", exchangeCount)
}
}
@@ -323,16 +349,17 @@ func TestRunStateElapsedUsesOpenAt(t *testing.T) {
}
}
// TestRunTargetsNotFoundBacksOff 验证未命中时不会每轮刷事件和列表请求。
// TestRunTargetsNotFoundBacksOff 验证未命中的每次真实尝试之间会退避。
func TestRunTargetsNotFoundBacksOff(t *testing.T) {
client := &fakeActivityClient{listResp: &huya.GetActPrizeListResp{Status: 200}}
runner := Runner{Client: client}
var notFound int32
started := time.Now()
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
{Name: "不存在的奖品"},
}, Config{
SID: 2203,
Loops: 6,
maxAttempts: 3,
Delay: time.Millisecond,
ErrorBackoff: 25 * time.Millisecond,
ListBeforeExchange: true,
@@ -344,12 +371,15 @@ func TestRunTargetsNotFoundBacksOff(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got := atomic.LoadInt32(&notFound); got != 1 {
t.Fatalf("not_found 事件=%d, want 1(退避期间应跳过)", got)
if got := atomic.LoadInt32(&notFound); got != 3 {
t.Fatalf("not_found 事件=%d, want 3 次真实尝试", got)
}
if elapsed := time.Since(started); elapsed < 45*time.Millisecond {
t.Fatalf("未命中退避没有生效,耗时=%v", elapsed)
}
}
// TestRunTargetsNotOpenBacksOff 验证未开放时也会退避,不会以 Delay 持续轰接口。
// TestRunTargetsNotOpenBacksOff 验证未开放的每次真实尝试之间也会退避。
func TestRunTargetsNotOpenBacksOff(t *testing.T) {
client := &fakeActivityClient{
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
@@ -357,19 +387,23 @@ func TestRunTargetsNotOpenBacksOff(t *testing.T) {
},
}
runner := Runner{Client: client}
started := time.Now()
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
{PID: 1},
}, Config{
SID: 2203,
Loops: 6,
maxAttempts: 3,
Delay: time.Millisecond,
ErrorBackoff: 25 * time.Millisecond,
}, nil)
if err != nil {
t.Fatal(err)
}
if _, exchangeCount, _ := client.counts(); exchangeCount != 1 {
t.Fatalf("exchangeCount=%d, want 1(未开放应退避)", exchangeCount)
if _, exchangeCount, _ := client.counts(); exchangeCount != 3 {
t.Fatalf("exchangeCount=%d, want 3 次真实尝试", exchangeCount)
}
if elapsed := time.Since(started); elapsed < 90*time.Millisecond {
t.Fatalf("未开放退避没有生效,耗时=%v", elapsed)
}
}
@@ -405,7 +439,7 @@ func TestRunTargetsDirectExchangeHonorsPriceFilter(t *testing.T) {
{PID: 1, MaxPrice: 50},
}, Config{
SID: 2203,
Loops: 1,
maxAttempts: 1,
Delay: time.Millisecond,
DirectExchange: true,
ListBeforeExchange: false,
@@ -441,7 +475,7 @@ func TestRunTargetsPrefireProbeIsBounded(t *testing.T) {
SID: 2203,
OpenAt: openAt,
windowOverride: 30 * time.Millisecond,
Loops: 1,
maxAttempts: 1,
Delay: time.Millisecond,
StartAhead: 20 * time.Millisecond,
Concurrency: 2,
@@ -465,13 +499,12 @@ func TestRunTargetsPrefireProbeIsBounded(t *testing.T) {
}
}
// TestRetryDelayNeverExceedsCap 验证全局降速和抖动不能把单次退避放大到上限之外。
// TestRetryDelayNeverExceedsCap 验证阶段倍率、连续失败倍率和抖动不会突破上限。
func TestRetryDelayNeverExceedsCap(t *testing.T) {
state := newRunState([]Account{{UID: 1}}, 1, 1, Config{})
state.governor = newThrottleGovernor()
state.governor.factor = governorMaxFactor
state.accounts[1].failStreak = 20
for i := 0; i < 20; i++ {
got := state.retryDelay(1, 0, Config{
got := state.retryDelay(1, Config{
ErrorBackoff: 300 * time.Millisecond,
TooFrequentBackoff: 300 * time.Millisecond,
}, CategoryTooFrequent)
@@ -496,7 +529,7 @@ func TestRunTargetsWindowModeKeepsTryingUntilDeadline(t *testing.T) {
SID: 2203,
OpenAt: started,
windowOverride: 120 * time.Millisecond,
Loops: 0, // 窗口模式:不限制轮次
maxAttempts: 0, // 窗口模式:不限制轮次
Delay: 5 * time.Millisecond,
ErrorBackoff: time.Millisecond,
TooFrequentBackoff: time.Millisecond,
@@ -533,7 +566,7 @@ func TestRunTargetsPrefireOnceBeforeOpen(t *testing.T) {
SID: 2203,
OpenAt: openAt,
windowOverride: 60 * time.Millisecond,
Loops: 0,
maxAttempts: 0,
Delay: 5 * time.Millisecond,
StartAhead: 20 * time.Millisecond,
ErrorBackoff: time.Millisecond,
@@ -571,7 +604,7 @@ func TestRunTargetsSkipsPrefireNearWindowStart(t *testing.T) {
SID: 2203,
OpenAt: openAt,
windowOverride: 40 * time.Millisecond,
Loops: 1, // 只跑一轮,用于观察首发是否被重复
maxAttempts: 1, // 只跑一轮,用于观察首发是否被重复
StartAhead: 60 * time.Millisecond,
}, nil)
if err != nil {
@@ -591,7 +624,7 @@ func TestRunTargetsWindowAlreadyExpiredSkips(t *testing.T) {
SID: 2203,
OpenAt: time.Now().Add(-2 * time.Second),
windowOverride: time.Second,
Loops: 0,
maxAttempts: 0,
}, nil)
if err != nil {
t.Fatal(err)
@@ -614,7 +647,7 @@ func TestRunTargetsSessionLostStopsAfterLimit(t *testing.T) {
runner := Runner{Client: client}
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
SID: 2203,
Loops: 10,
maxAttempts: 10,
Delay: 2 * time.Millisecond,
ErrorBackoff: time.Millisecond,
SessionLostLimit: 3,
@@ -639,7 +672,7 @@ func TestRunTargetsSummaryIncludesRequestAndAccountStats(t *testing.T) {
runner := Runner{Client: client, OnSummary: func(item RunSummary) { summary = item }}
err := runner.RunTargets(context.Background(), []Account{{UID: 7, Cookie: "yyuid=7"}}, []Target{{PID: 12889}}, Config{
SID: 2203,
Loops: 2,
maxAttempts: 2,
Delay: time.Millisecond,
ErrorBackoff: time.Millisecond,
StopAfterSuccess: true,
@@ -742,7 +775,7 @@ func TestRunTargetsPerAccountLoopsAreIndependent(t *testing.T) {
go func() {
done <- runner.RunTargets(context.Background(), accounts, []Target{{PID: 12889}}, Config{
SID: 2203,
Loops: 30,
maxAttempts: 30,
Delay: time.Millisecond,
ErrorBackoff: time.Millisecond,
TooFrequentBackoff: time.Millisecond,
@@ -792,7 +825,7 @@ func TestRunTargetsSharedListTTLSingleFlight(t *testing.T) {
err := runner.RunTargets(context.Background(), accounts, []Target{{Name: "小黄鸭"}}, Config{
SID: 2203,
Loops: 3,
maxAttempts: 3,
Delay: time.Millisecond,
ErrorBackoff: time.Millisecond,
TooFrequentBackoff: time.Millisecond,
@@ -833,11 +866,11 @@ func TestRunStateAccountFinishedAndRoundTracking(t *testing.T) {
if state.accountFinished(1, 2) {
t.Fatal("目标都没完成时不应判定账号结束")
}
state.accounts[1][0].Done = true
state.accounts[1].targets[0].Done = true
if state.accountFinished(1, 2) {
t.Fatal("还有一个目标未完成时不应判定账号结束")
}
state.accounts[1][1].Done = true
state.accounts[1].targets[1].Done = true
if !state.accountFinished(1, 2) {
t.Fatal("所有目标完成后应判定账号结束")
}
@@ -849,11 +882,11 @@ func TestRunStateAccountFinishedAndRoundTracking(t *testing.T) {
t.Fatal("全局目标已终止时账号应判定结束")
}
rounds := newRunState([]Account{{UID: 3}}, 1, 1, Config{})
rounds.noteRound(3)
rounds.noteRound(2)
rounds.noteRound(7)
if got := rounds.maxRound(); got != 7 {
maxAttemptCount := newRunState([]Account{{UID: 3}}, 1, 1, Config{})
maxAttemptCount.noteAttempt(3)
maxAttemptCount.noteAttempt(2)
maxAttemptCount.noteAttempt(7)
if got := maxAttemptCount.maxAttempt(); got != 7 {
t.Fatalf("最大轮次=%d, want 7", got)
}
}