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
+52 -44
View File
@@ -66,7 +66,6 @@ type Config struct {
MinLeft int64 `json:"minLeft"`
CookieText string `json:"cookieText"`
SelectedAccountLines []int `json:"selectedAccountLines"`
Loops int `json:"loops"`
DelayMS int `json:"delayMs"`
Concurrency int `json:"concurrency"`
StopAfterSuccess bool `json:"stopAfterSuccess"`
@@ -83,12 +82,8 @@ type Config struct {
ErrorBackoffMS int `json:"errorBackoffMs"`
TimeoutSec int `json:"timeoutSec"`
StartAt string `json:"startAt"`
// WindowSeconds 是抢购窗口长度(秒):窗口模式下跑到「开抢 + 窗口」才收工,
// 账号少时也不会像旧实现那样在开抢前把轮次烧光。<=0 时取默认 30 秒。
// WindowSeconds 是抢购窗口长度(秒):跑到「开抢 + 窗口」才收工。
WindowSeconds int `json:"windowSeconds"`
// DisableAdaptiveThrottle 关闭全局自适应降速(默认开启,故用反向字段):
// 连续十几个请求都拿不到业务响应时整体降速,缓解同机同 IP 的限流风暴。
DisableAdaptiveThrottle bool `json:"disableAdaptiveThrottle"`
}
type AccountPreview struct {
@@ -302,15 +297,18 @@ func (a *App) Shutdown(ctx context.Context) {
func (a *App) DefaultConfig() Config {
return Config{
Transport: "wss",
WSSHost: "",
SID: 2203,
Loops: 20,
DelayMS: 120,
Concurrency: 5,
Transport: "wss",
WSSHost: "",
SID: 2203,
DelayMS: 120,
// 线程是「同时在途请求数」,不是账号槽位;多开时同一台机器的总请求速率
// 约为 线程 × 实例数 / 平均 RTT。2026-10-17 的 24 个任务用了旧默认 5,
// 峰值合集约 400~600 请求/秒、84% 被限流,所以默认压到 2,优先换取
// 服务端真正受理请求的概率。账号很多时仍可在界面显式调高。
Concurrency: 2,
StopAfterSuccess: false,
StopAccountAfterSuccess: true,
Prewarm: true,
Prewarm: false,
DirectExchange: true,
SharePrizeList: true,
AutoSelect: false,
@@ -505,9 +503,9 @@ func (a *App) StartMonitor(cfg Config) error {
}
a.emitState(true, "运行中")
a.addLog("info", "启动监控: sid=%d 类目=%s targets=%d 目标=%s accounts=%d prewarm=%v direct=%v 窗口=%s 自适应降速=%v",
a.addLog("info", "启动监控: sid=%d 类目=%s targets=%d 目标=%s accounts=%d prewarm=%v direct=%v 窗口=%s",
cfg.SID, sniper.CategoryText(cfg.Category), len(targets), sniper.TargetSummary(targets), len(accounts),
cfg.Prewarm, cfg.DirectExchange, sniper.WindowDuration(cfg.WindowSeconds), !cfg.DisableAdaptiveThrottle)
cfg.Prewarm, cfg.DirectExchange, sniper.WindowDuration(cfg.WindowSeconds))
go func() {
defer closeClient()
@@ -548,23 +546,37 @@ func (a *App) StartMonitor(cfg Config) error {
if err := a.waitFor(ctx, plan.ResyncAt, "复校"); err != nil {
return
}
calibration, calErr := huya.TryCalibrateServerTime(ctx, client, accounts[0].UID, accounts[0].Cookie, huya.DefaultTimeCalibrationRounds)
// 校准最多占用到触发时刻:服务器繁忙时 pingSignal 可能连续超时,
// 不能让它把真正的开抢时间整体拖后。
calCtx, calCancel := context.WithDeadline(ctx, plan.TriggerAt)
calibration, calErr := huya.TryCalibrateServerTime(calCtx, client, accounts[0].UID, accounts[0].Cookie, huya.DefaultTimeCalibrationRounds)
calCancel()
if ctx.Err() != nil {
return
}
if calErr != nil {
logger.SetServerOffset(0)
a.addLog("warn", "时间校准失败,按本机时钟触发: %v", calErr)
} else {
plan = sniper.PlanTrigger(startAt, calibration, lead, window)
logger.SetServerOffset(calibration.Offset)
a.addLog("info", "时间校准完成: %s", calibration.Summary())
}
}
if cfg.Prewarm {
if err := a.waitFor(ctx, plan.WarmupAt, "预热"); err != nil {
return
}
a.addLog("info", "开始预热连接: accounts=%d(距触发 %s)", len(accounts), time.Until(plan.TriggerAt).Round(time.Millisecond))
if err := runner.Prewarm(ctx, accounts, runnerCfg, emit); err != nil {
a.addLog("error", "连接预热异常: %v", err)
return
}
// 预热在独立后台协程运行,绝不阻塞主发令枪:
// 无论预热成功与否、耗时多久,主定时器到达 TriggerAt 立即开抢。
prewarmCtx, prewarmCancel := context.WithDeadline(ctx, plan.TriggerAt)
go func() {
defer prewarmCancel()
if err := a.waitFor(prewarmCtx, plan.WarmupAt, "预热"); err != nil {
return
}
a.addLog("info", "开始预热连接: accounts=%d(距触发 %s)", len(accounts), time.Until(plan.TriggerAt).Round(time.Millisecond))
if err := runner.Prewarm(prewarmCtx, accounts, runnerCfg, emit); err != nil && prewarmCtx.Err() == nil {
a.addLog("warn", "预热未在触发前完成,继续抢购(未完成账号将在首次请求时建连): %v", err)
}
}()
}
runnerCfg.OpenAt = plan.OpenAt
a.addLog("info", "等待定时开始: 触发=%s 开抢=%s 窗口结束=%s 提前=%dms 首发错峰=%dms",
@@ -577,6 +589,9 @@ func (a *App) StartMonitor(cfg Config) error {
a.addLog("info", "定时等待已取消")
return
}
if late := time.Since(plan.TriggerAt); late > 50*time.Millisecond {
a.addLog("warn", "实际触发比计划晚 %s(触发=%s)", late.Round(time.Millisecond), plan.TriggerAt.Format("15:04:05.000"))
}
a.runMonitor(ctx, runner, accounts, targets, runnerCfg, emit)
}()
return nil
@@ -618,7 +633,6 @@ func runnerConfig(cfg Config) sniper.Config {
return sniper.Config{
SID: cfg.SID,
Category: cfg.Category,
Loops: cfg.Loops,
Delay: time.Duration(cfg.DelayMS) * time.Millisecond,
Concurrency: cfg.Concurrency,
StopAfterSuccess: cfg.StopAfterSuccess,
@@ -632,9 +646,8 @@ func runnerConfig(cfg Config) sniper.Config {
ErrorBackoff: time.Duration(cfg.ErrorBackoffMS) * time.Millisecond,
WindowSeconds: cfg.WindowSeconds,
// 首发错峰固定用调优过的默认值:同机上百个账号齐射是最容易被限流的姿势。
FirstWaveSpread: sniper.DefaultFirstWaveSpread,
FirstWaveMaxStep: sniper.DefaultFirstWaveMaxStep,
DisableAdaptiveThrottle: cfg.DisableAdaptiveThrottle,
FirstWaveSpread: sniper.DefaultFirstWaveSpread,
FirstWaveMaxStep: sniper.DefaultFirstWaveMaxStep,
}
}
@@ -652,10 +665,10 @@ func (a *App) logRunSummary(summary sniper.RunSummary) {
if !summary.OpenAt.IsZero() {
window = fmt.Sprintf(" 开抢=%s 窗口=%ds", summary.OpenAt.Format("15:04:05.000"), summary.WindowSeconds)
}
a.addLog("info", "任务结束: 轮次=%d 账号=%d 目标=%d 成功账号=%d 耗时=%s 限流=%d/%d(%d%%) 降速=×%.1f 请求[列表=%d 兑换=%d 积分=%d 记录=%d]%s",
summary.Loops, summary.Accounts, summary.Targets, summary.SuccessUIDs,
a.addLog("info", "任务结束: 最大尝试=%d 账号=%d 目标=%d 成功账号=%d 耗时=%s 限流=%d/%d(%d%%) 请求[列表=%d 兑换=%d 积分=%d 记录=%d]%s",
summary.Attempts, summary.Accounts, summary.Targets, summary.SuccessUIDs,
summary.Duration.Round(time.Millisecond),
throttled, total, percentOf(throttled, total), throttleFactorText(summary.ThrottleFactor),
throttled, total, percentOf(throttled, total),
summary.ListReqs, summary.ExchangeReqs, summary.ScoreReqs, summary.RecordReqs, window)
for _, category := range summary.Categories() {
a.logEvent(categoryMonitor, sniper.LogLevelForCategory(category), "结局 %s ×%d(%s)",
@@ -690,14 +703,6 @@ func percentOf(part, whole int) int {
return part * 100 / whole
}
// throttleFactorText 渲染自适应降速倍率。
func throttleFactorText(factor float64) float64 {
if factor < 1 {
return 1
}
return factor
}
func (a *App) StopMonitor() bool {
a.runMu.Lock()
cancel := a.monitorCancel
@@ -774,10 +779,6 @@ func normalizeConfig(cfg Config) Config {
cfg.Transport = "wss"
}
// WSSHost 留空表示走 launch.queryHttpDns 自动解析,不在这里补默认值。
// Loops 只作为可选上限:0(留空)表示「按窗口运行」,由 WindowSeconds 兜底。
if cfg.Loops < 0 {
cfg.Loops = 0
}
if cfg.DelayMS <= 0 {
cfg.DelayMS = 150
}
@@ -953,13 +954,20 @@ func nextClockTime(now time.Time, hour, minute, second int) time.Time {
// waitUntil 等到指定时刻。用一次性定时器精确睡眠,避免旧实现 200ms 轮询带来的
// 0-200ms 随机延迟(抢购时这段时间正好是关键窗口)。
//
// 长等待拆成最多 1 秒一段:部分 Windows 机器上几小时的单个定时器会被系统合并/延迟,
// 今天日志里就出现过“等待 2 小时后复校晚到 5~8 秒”的实例。
func waitUntil(ctx context.Context, when time.Time) error {
for {
remaining := time.Until(when)
if remaining <= 0 {
return nil
}
timer := time.NewTimer(remaining)
chunk := remaining
if chunk > time.Second {
chunk = time.Second
}
timer := time.NewTimer(chunk)
select {
case <-timer.C:
case <-ctx.Done():
+11 -5
View File
@@ -68,9 +68,16 @@ func TestParseAccountsRequiresExplicitSelection(t *testing.T) {
}
}
func TestDefaultConfigUsesDynamicLead(t *testing.T) {
if got := (&App{}).DefaultConfig().LeadMS; got != 0 {
t.Fatalf("LeadMS=%d, want 0(动态提前量)", got)
func TestDefaultConfigUsesWindowMode(t *testing.T) {
cfg := (&App{}).DefaultConfig()
if cfg.LeadMS != 0 {
t.Fatalf("LeadMS=%d, want 0(动态提前量)", cfg.LeadMS)
}
if cfg.Concurrency != 2 {
t.Fatalf("Concurrency=%d, want 2(降低多开时的请求洪峰)", cfg.Concurrency)
}
if cfg.Prewarm {
t.Fatal("Prewarm 应默认关闭,避免开抢前因单账号建连超时阻塞")
}
}
@@ -170,7 +177,6 @@ func TestParseTargetsWithoutFiltersKeepsZeroValues(t *testing.T) {
func TestRunnerConfigMapsDirectExchangeToExchangeMode(t *testing.T) {
direct := runnerConfig(Config{
SID: 2203,
Loops: 3,
DelayMS: 120,
Concurrency: 5,
DirectExchange: true,
@@ -178,7 +184,7 @@ func TestRunnerConfigMapsDirectExchangeToExchangeMode(t *testing.T) {
if !direct.DirectExchange || direct.ListBeforeExchange {
t.Fatalf("直接兑换模式映射错误: %+v", direct)
}
if direct.SID != 2203 || direct.Loops != 3 || direct.Delay != 120*time.Millisecond || direct.Concurrency != 5 {
if direct.SID != 2203 || direct.Delay != 120*time.Millisecond || direct.Concurrency != 5 {
t.Fatalf("基础字段未透传: %+v", direct)
}