Compare commits
5
Commits
d21b06a311
...
2451466bed
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2451466bed | ||
|
|
8b3b14654f | ||
|
|
29aed15e4e | ||
|
|
828236eb1d | ||
|
|
0294606807 |
@@ -1,22 +1,14 @@
|
||||
# huya-go
|
||||
|
||||
虎牙活动积分兑换/抢购的 Go 复刻版。支持两种传输层,CLI 与 GUI 默认都走 `wss`:
|
||||
虎牙活动积分兑换/抢购的 Go 复刻版(Wails 桌面应用)。支持两种传输层,默认走 `wss`:
|
||||
|
||||
- `wss`(默认):浏览器实际使用的通道。先调用 `launch.queryHttpDns` 解析可用 host,再走 TAF `WebSocketCommand` 外层与 WSS 初始化流程(`launch.wsLaunch` → `mobileui.getConfig`)。host 留空即自动解析,解析失败会回退内置默认 host。
|
||||
- `http`:走 `https://cdnws.api.huya.com/`,作为可回退通道;CLI 用 `-transport http`,GUI 在设置里切换。
|
||||
- `http`:走 `https://cdnws.api.huya.com/`,作为可回退通道,在设置里切换。
|
||||
|
||||
## 构建
|
||||
|
||||
CLI:
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
go build -o huya-go ./cmd/huya-go
|
||||
```
|
||||
|
||||
GUI:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run typecheck
|
||||
@@ -45,43 +37,15 @@ yyuid=...; udb_uid=...; guid=...; ...
|
||||
|
||||
不要把 Cookie、token、JWT 提交到仓库或写进文档。
|
||||
|
||||
## 常用命令
|
||||
## 常用操作
|
||||
|
||||
GUI 界面提供账号预览、奖品列表、积分查询、兑换记录、直接兑换、监控抢购、实时日志。
|
||||
界面提供账号预览、奖品列表、积分查询、兑换记录、直接兑换、监控抢购、实时日志:
|
||||
|
||||
CLI 示例:
|
||||
|
||||
查询奖品列表:
|
||||
|
||||
```bash
|
||||
./huya-go -cmd list -sid 2203 -cookie-file cookie.txt
|
||||
```
|
||||
|
||||
查询积分:
|
||||
|
||||
```bash
|
||||
./huya-go -cmd score -sid 2203 -cookie-file cookie.txt
|
||||
```
|
||||
|
||||
直接兑换指定 PID:
|
||||
|
||||
```bash
|
||||
./huya-go -cmd exchange -sid 2203 -pid 12889 -cookie-file cookie.txt
|
||||
```
|
||||
|
||||
按奖品名轮询并抢购:
|
||||
|
||||
```bash
|
||||
./huya-go -cmd monitor -sid 2203 -name 小黄鸭 -cookie-file cookie.txt -loops 20 -delay 120 -concurrency 5
|
||||
```
|
||||
|
||||
定时开始:
|
||||
|
||||
```bash
|
||||
./huya-go -cmd monitor -sid 2203 -pid 12889 -cookie-file cookie.txt -at "2026-07-06 20:00:00"
|
||||
```
|
||||
|
||||
以上默认都走 `wss`。需要回退到 http 传输时,给任意命令加上 `-transport http`。
|
||||
- **查奖品列表**:填好 SID 与账号后点「获取商品」,列表按类目分页签(全部 / 限量返场 / 精英专享,带商品数),未上架商品显示上架时间与倒计时。
|
||||
- **查积分 / 兑换记录**:在商品列表里按行查询;行内还能直接对单个 PID 发起兑换。
|
||||
- **抢购**:选中账号 + 填写目标(PID 或奖品名,可配合「最高积分」「最少库存」「自动选品」),点「监控抢购」进入窗口循环。
|
||||
- **定时抢购**:填写「开始时间」即可,支持 `2026-07-06 20:00:00`、`20:00:00`、RFC3339;开启「时间校准」时按服务端时间理解。
|
||||
- **传输**:默认 `wss`;需要回退到 http 时在设置里把「传输」切成 `http`。
|
||||
|
||||
## 多开(多实例)
|
||||
|
||||
@@ -95,35 +59,78 @@ CLI 示例:
|
||||
|
||||
## 日志
|
||||
|
||||
GUI 与 CLI 共用同一套结构化日志(分类 + 等级 + 账号标签),同时输出到界面与磁盘:
|
||||
结构化日志(分类 + 等级 + 账号标签)同时输出到界面与磁盘:
|
||||
|
||||
- 路径:`<数据目录>/logs/huya-go_<实例标识>_<时间戳>.log`。macOS 数据目录为 `~/Library/Application Support/huya-go`,Windows 为 `%AppData%\huya-go`。
|
||||
- 每次启动创建独立文件(`O_EXCL` 抢占,重名自动加 `-2` 后缀),所以多开或同秒重启都不会写进同一个文件;文件开头写明实例名、数据目录与格式说明。
|
||||
- 单文件上限 5MB,超出后滚动为 `.1` ~ `.5`,最旧的被丢弃。
|
||||
- 每行格式:`时间 [分类][等级][账号] 正文`。逐条网络请求是 `debug` 级,默认不记录,可在界面「日志」页签打开「调试」开关,或 CLI 使用 `-log-level debug`。
|
||||
- 每行格式:`时间 [分类][等级][账号] 正文`。逐条网络请求是 `debug` 级,默认不记录,可在「日志」页签用「调试日志」开关打开(等级也可由环境变量 `HUYA_LOG_LEVEL` 覆盖)。
|
||||
- 写盘是异步且队列有界:队列满时丢弃日志并在文件尾部与界面提示丢弃条数,避免磁盘 I/O 拖慢抢购链路。
|
||||
- 界面「日志」页签支持按等级筛选、按 ID 增量拉取、一键打开日志目录或复制路径。
|
||||
- GUI 启动失败(例如 WebView2 建不出环境)时,`<用户缓存目录>/huya-go/startup.log` 会记录原因。
|
||||
|
||||
## 参数说明
|
||||
## 设置项说明
|
||||
|
||||
- `-cmd`:`list`、`score`、`records`、`exchange`、`monitor`。
|
||||
- `-sid`:活动 SID,必填。
|
||||
- `-pid`:奖品 PID。`exchange` 必填,`monitor` 可用 `-pid` 或 `-name`。
|
||||
- `-max-price`:目标奖品最高积分,`0` 表示不限制(CLI 与 GUI 设置都支持)。
|
||||
- `-min-left`:目标奖品最少剩余库存,`0` 表示不限制(CLI 与 GUI 设置都支持)。
|
||||
- `-category`:类目过滤,支持类目名(如 `限量返场`、`精英专享`)或类目 id(如 `99`);留空表示不限。
|
||||
- `-category-only`:`list` 只输出该类目的商品(配合 `-category` 使用)。
|
||||
- `-cookie`:单账号 Cookie。
|
||||
- `-cookie-file`:多账号 Cookie 文件。
|
||||
- `-transport`:`wss` 或 `http`,默认 `wss`。
|
||||
- `-wss-host`:WebSocket host。默认留空,自动调用 `launch.queryHttpDns` 解析(带 TTL 缓存、多 host 轮询),解析失败时回退内置默认 host;需要固定时可显式指定。
|
||||
- `-timeout`:单次调用超时秒数。
|
||||
- `-loops`、`-delay`、`-concurrency`:轮询次数、轮询间隔、并发账号数。
|
||||
- `-stop-after-success`:`monitor` 中任一账号成功后是否停止。
|
||||
- `-log-dir`:日志目录,默认使用应用数据目录下的 `logs`。
|
||||
- `-log-level`:日志最低等级,`debug`/`info`/`warn`/`error`,默认 `info`。
|
||||
- `-v`:输出调试日志(等价于 `-log-level debug`,并把网络日志同时打到 stderr)。
|
||||
界面设置对应 `internal/gui` 的 `Config`:
|
||||
|
||||
- **传输**:`wss`(默认)或 `http`。
|
||||
- **WSS Host**:默认留空,自动调用 `launch.queryHttpDns` 解析(带 TTL 缓存、多 host 轮询),解析失败时回退内置默认 host;需要固定时可显式指定。
|
||||
- **SID**:活动 SID,必填。
|
||||
- **PID / 目标**:奖品 PID;监控时也可以用奖品名(支持模糊匹配)。
|
||||
- **最高积分 / 最少库存**:目标奖品的价格上限与剩余库存下限,`0` 表示不限制。
|
||||
- **次数上限**:`0`(默认)表示按窗口运行,由「窗口秒」兜底;填了就作为单个账号的轮次上限。
|
||||
- **窗口秒**:抢购窗口长度,默认 `30`。窗口模式下跑到「开抢 + 窗口」才收工(详见「窗口调度」)。
|
||||
- **延时**:单个账号两轮之间的间隔(毫秒)。账号之间互不等待,所以它只决定单个账号的节奏。
|
||||
- **线程**:限制**同时在途的请求数**(不是同时运行的账号数);账号在退避等待期间不占用额度。
|
||||
- **提前**:相对开始时间的提前量,`0` = 按服务端时钟校准误差动态计算(`误差上界 + RTT/2`,下限 50ms);填了就用固定提前量。
|
||||
- **预热 / 直兑 / 共享列表 / 自动选品 / 账号成功停 / 成功刷新**:见「抢购调度」。
|
||||
- **时间校准**:默认开启。定时前用 `launch.pingSignal` 校准服务端与本机的钟差,并把触发时刻对齐到服务端时钟(详见「时间校准」)。
|
||||
- **自适应降速**:默认开启。连续十几个请求都拿不到业务响应时整体降速(最多 4 倍),一旦恢复进展立刻回退。
|
||||
- **开始时间**:定时开始时间,支持 `RFC3339`、`2006-01-02 15:04:05`、`HH:MM:SS`;开启时间校准时按**服务端时间**理解。
|
||||
- **超时**:单次调用超时秒数。
|
||||
|
||||
## 抢购调度与退避(2026-10-16 调整)
|
||||
|
||||
参考 `dygou_go` 的抢购调度经验(该项目的实测复盘结论)做了以下调整:
|
||||
|
||||
- **每个账号独立循环**:账号各自在自己的 goroutine 里按「延时」节奏重试,互不等待、互不阻塞。旧实现按「一轮打完等所有人」(`wg.Wait`)同步,某个账号卡在慢请求上时,其余账号这一轮只能干等——账号少的实例尤其吃亏(pc-3 instance-4 因此 0 成功)。请求速率由请求级并发闸门兜底。
|
||||
- **并发额度按单次请求计**:额度只覆盖一次在途请求,账号在退避等待期间释放额度。旧实现把额度给整个账号循环,退避中的账号会一直霸占额度,账号多时互相饿死。
|
||||
- **售罄不再默认终止**:服务端回「已抢完 / 库存不足」时继续按退避节奏探测到轮询结束——别人锁单未支付或取消会让库存回流。需要「售罄即停」时显式设置 `Config.StopOnSoldOut`。
|
||||
- **下架仍然终止**:`已下架 / 奖品不存在` 视为本窗口内的终态,直接停止该奖品(与售罄区别对待)。
|
||||
- **积分不足仍然终止**:积分不会自己变多,默认 `StopOnNotEnough`,避免无意义的重复请求。
|
||||
- **退避带抖动**:所有退避(限频 / 失败 / 售罄探测)在配置值基础上叠加 0-25% 随机抖动,避免多个账号在同一时刻整批重试形成周期性尖峰;配置值始终是退避下限。
|
||||
- **定时精确触发**:定时开抢改用一次性定时器(旧实现按 200ms 轮询,醒来时刻会随机晚 0-200ms,正好错过开抢窗口)。「提前」仍用于按 RTT 提前起跑。
|
||||
- **任务结束汇总**:每次监控结束输出一行汇总(轮次 / 账号 / 目标 / 成功账号 / 耗时 / 请求次数)与按次数排序的结局分布(`success`、`sold_out`、`too_frequent`、`not_found` 等),便于复盘。
|
||||
- **HTTP 传输连接池**:`http` 传输补上 `MaxConnsPerHost=64`、`MaxIdleConnsPerHost=64`(Go 默认每主机只有 2 个空闲连接),多账号并发时不再反复重建连接。
|
||||
|
||||
### 0.4.0:窗口调度 / 限流分类 / 可观测性(2026-10-16 三机复盘)
|
||||
|
||||
依据 2026-10-16 三台机器同一场活动的真实日志(247 账号、2000 次兑换请求):
|
||||
|
||||
- **每账号独立循环**:正式窗口里每个账号一个 goroutine 跑自己的循环,直到窗口结束或自己打完(所有目标成功 / 进入终态)。旧实现是「一轮打完等所有人」,慢账号会拖住全部账号的节奏;「延时」从此只决定**单个账号**的节奏。
|
||||
- **共享列表 TTL + 单飞**:「共享列表」打开时,同一时刻只有一个账号去查奖品列表,其余账号在 1 秒 TTL 内复用同一份成功快照(失败不缓存,避免一次抖动让所有账号一起失败)。pc-1 的 152 个账号从每轮 152 次查询降到 1 次。
|
||||
- **窗口调度取代轮次预算**:终止条件从「轮次 × 间隔」改为「开抢 + 窗口秒数」(默认 30s)。旧实现里 `Delay=150ms` 时 1 个账号的 20 轮只有 3.1 秒,会把预算全部烧在开抢之前(当天 pc-3 instance-4 一轮都没打进窗口,0 成功)。GUI 的「次数上限」退化为可选上限,留空即按窗口运行。
|
||||
- **开抢前只预打一轮**:开抢前若还没到点,先补一轮探活请求,随后静默等到「开抢 − 60ms」再进入窗口循环。旧实现把 2.5s 提前量整段用来循环重试,实测 1421 次请求里 82% 被限流挡回。
|
||||
- **动态提前量 + 临近复校**:触发提前量 = `误差上界 + RTT/2`(下限 50ms),并在开抢前 3s 复校一次时钟、2s 前预热连接(顺序与 `sniper.PlanTrigger` 统一)。
|
||||
- **首发错峰**:第 0 个账号立即发,其余按 `min(300ms/(n-1), 8ms)` 依次错开,避免同机上百账号在同一毫秒齐射。
|
||||
- **退避阶梯**:基础退避随时间分档放大(<2s ×1、<5s ×2、≥5s ×3),同一账号连续失败第 3 次起翻倍(上限 ×4),再乘全局降速倍率并叠加 0-25% 抖动;任何一次等待都不超过 1.5s(超过就可能错过库存回流)。
|
||||
- **全局自适应降速(默认开)**:连续 12 个以上请求都拿不到业务响应且持续 800ms 时,整体退避按 1.5 倍逐级放大(上限 4 倍),一旦有进展立即回退。触发信号刻意选「无进展」而不是「限流占比」——实测即使成功率 97.6% 的那次也有 67% 请求被限流,用占比阈值会把正常运行的机器一起拖慢。GUI 设置里的「自适应降速」可关。
|
||||
- **限流分类补全**:「活动太火爆 / 领取频率限制 / 网络繁忙 / 点击太快 / 排队…」统一归入 `too_frequent`,并按「未开放 → 售罄 → 货币不足 → 会话失效 → 下架 → 限流」的固定顺序判定(过去这些文案全落到 `failed`,看不出被限流)。新增 `session_lost`(「账号未绑定!」,瞬时错误,连续 3 次才停止该账号)与 `protocol`(回包缺 `tRsp/tResp`)两个分类。
|
||||
- **协议错误可观测**:`wup.Response.Diagnose()` 把 `iRet / servant / status / context / keys / payload` 一并带进报错;debug 级日志打印原始帧前缀(32B HEX)。此前只有一句「响应缺少 tRsp/tResp」,同一账号连续 13 次命中也无法定性。
|
||||
- **复盘日志**:任务结束输出「一行总量(含限流占比与降速倍率)+ 结局分布(带中文标签)+ 接口统计(次数/失败/平均/最慢/最后错误)+ 每个账号一行最终结局」;`启动监控` 带上目标 `pid(名称)`(此前只有 `targets=1`,无法判断三台机器打的是否同一个奖品)。
|
||||
|
||||
## 时间校准(2026-10-16 新增)
|
||||
|
||||
定时抢购默认先做一次服务端时间校准(GUI 设置里的「时间校准」开关,默认开):
|
||||
|
||||
- **数据来源**:`launch.pingSignal` 响应里的 `signal_ap_start` / `signal_ap_end`。2026-10-13 抓包确认这两个字段是 Unix 毫秒时间戳(`start` 是服务端收到请求的时刻,`end` 是写出响应的时刻,实测相差 13ms);真实字节夹具见 `internal/huya/launch_test.go` 的 `realPingSignalRspHex`。
|
||||
- **钟差估计**:`偏移 = signal_ap_start − (发送时刻 + RTT/2)`,误差上界取 `RTT/2`——服务端打时间戳的具体位置落在发送与接收之间,无法再精确,按最坏情况估计。
|
||||
- **多轮取优**:默认 3 轮采样,取「误差上界最小、其次 RTT 最低」的样本;再对最近 3 次偏移取中位数平滑,压掉单轮网络抖动。
|
||||
- **生效方式**:「开始时间」(`startAt`)按服务端时间理解,触发时刻 = `目标时刻 − 提前量 − 偏移`。本机时钟比服务端慢 300ms 就自动提前 300ms,反之推后。
|
||||
- **失败降级**:一次样本都拿不到时只告警,仍按本机时钟触发;时间戳明显不合理(解析出来不是这个世纪的毫秒值)会被丢弃,避免按错误偏移整体挪走抢购窗口。
|
||||
- **日志**:`时间校准完成: 服务端=2026-10-16 20:00:01.234 本机偏移=+123ms 误差<=45ms RTT=90ms 样本=3 已平滑`。
|
||||
|
||||
校准每次只多花几百毫秒(3 轮 pingSignal),发生在**开抢前 3 秒**(预热在开抢前 2 秒,触发在开抢前 `advance`),因此既不会挤占开抢窗口,也不会因为启动过早让偏移过期。
|
||||
|
||||
## 已确认的小黄鸭参数
|
||||
|
||||
@@ -146,7 +153,7 @@ GUI 与 CLI 共用同一套结构化日志(分类 + 等级 + 账号标签)
|
||||
- 消耗积分:`20`
|
||||
- 订单号格式:`sOrderId_2277_13409_<uid>_<时间戳>_<随机>`
|
||||
|
||||
该活动的列表/积分/兑换接口与 `sid=2203` 走同一套 `webActUI`,可直接用 `-cmd list -sid 2277` 验证;同一次抓包里「开通精英宝典 / 购买精英币」属于商城付费链路(`shopMiddleUI.*` + 支付宝),本项目未实现,详见 `WSS_NOTES.md`。
|
||||
该活动的列表/积分/兑换接口与 `sid=2203` 走同一套 `webActUI`,把 SID 改成 `2277` 即可在界面里验证;同一次抓包里「开通精英宝典 / 购买精英币」属于商城付费链路(`shopMiddleUI.*` + 支付宝),本项目未实现,详见 `WSS_NOTES.md`。
|
||||
|
||||
## 商品类目:限量返场 / 精英专享(2026-10-15 抓包)
|
||||
|
||||
@@ -158,18 +165,11 @@ GUI 与 CLI 共用同一套结构化日志(分类 + 等级 + 账号标签)
|
||||
- 限量返场是「预告上架」类商品:`start_time`(TAF tag25,实测 2026-10-16 17:00:00)与 `end_time`(tag26)决定
|
||||
可兑换时间窗,页面上的「xx:xx:xx 后上架」倒计时就来自它;`daily_start/daily_end`(tag27/28)是每日可兑时段。
|
||||
|
||||
用法:
|
||||
用法(界面「商品列表」):
|
||||
|
||||
```bash
|
||||
# 全量列表(日志里会打出「类目=精英专享(101)=18项/限量返场(99)=12项」)
|
||||
./huya-go -cmd list -sid 2277 -cookie-file cookies.txt
|
||||
- **全量列表**:SID 填 `2277` 点「获取商品」,日志里会打出「类目=精英专享(101)=18项/限量返场(99)=12项」。
|
||||
- **只看某个类目**:在商品列表上方切换类目页签,或点某个类目标签过滤(也支持类目 id 或模糊名,如 `99` / `返场`)。
|
||||
- **限定类目抢购**:选中类目并打开「自动选品」,当前类目会一起提交给监控,作为自动选品的范围。
|
||||
|
||||
# 只看限量返场(也支持类目 id 或模糊名,如 -category 99 / -category 返场)
|
||||
./huya-go -cmd list -sid 2277 -cookie-file cookies.txt -category 限量返场 -category-only
|
||||
|
||||
# 抢购时限定只在该类目里选品(配合 -auto)
|
||||
./huya-go -cmd monitor -sid 2277 -cookie-file cookies.txt -category 限量返场 -auto
|
||||
```
|
||||
|
||||
界面「商品列表」同样按类目分了页签(全部 / 限量返场 / 精英专享,带商品数),每行标注类目,
|
||||
界面「商品列表」按类目分了页签(全部 / 限量返场 / 精英专享,带商品数),每行标注类目,
|
||||
未上架的商品显示上架时间与倒计时;当前选中的类目会一起提交给监控,用作自动选品的范围。
|
||||
|
||||
@@ -1,416 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
"huya-go/internal/instance"
|
||||
"huya-go/internal/logger"
|
||||
"huya-go/internal/sniper"
|
||||
)
|
||||
|
||||
// closeLogger 由 logger.Init 返回;os.Exit 不会执行 defer,退出前必须显式刷盘。
|
||||
var closeLogger func()
|
||||
|
||||
const (
|
||||
categoryNet = "网络"
|
||||
categoryMonitor = "监控"
|
||||
categoryCLI = "CLI"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var (
|
||||
cmd = flag.String("cmd", "list", "命令:list/score/records/exchange/monitor")
|
||||
cookie = flag.String("cookie", "", "虎牙 Cookie")
|
||||
cookieFile = flag.String("cookie-file", "", "Cookie 文件,一行一个账号")
|
||||
sid = flag.Int("sid", 0, "活动 SID")
|
||||
category = flag.String("category", "", "类目过滤:类目名(如 限量返场)或类目 id,留空表示不限")
|
||||
categoryOnly = flag.Bool("category-only", false, "list 只输出指定类目的商品")
|
||||
pid = flag.Int("pid", 0, "奖品 PID")
|
||||
pids = flag.String("pids", "", "多个奖品 PID,逗号分隔")
|
||||
name = flag.String("name", "", "按奖品名包含匹配")
|
||||
names = flag.String("names", "", "多个奖品名,逗号分隔")
|
||||
maxPrice = flag.Int64("max-price", 0, "目标奖品最高积分,0 表示不限制")
|
||||
minLeft = flag.Int64("min-left", 0, "目标奖品最少剩余库存,0 表示不限制")
|
||||
autoSelect = flag.Bool("auto", false, "monitor 自动选择列表里的可兑奖品")
|
||||
loops = flag.Int("loops", 1, "monitor 循环次数")
|
||||
delayMS = flag.Int("delay", 150, "monitor 每轮间隔毫秒")
|
||||
concurrency = flag.Int("concurrency", 5, "monitor/exchange 并发账号数")
|
||||
stopAfterSuccess = flag.Bool("stop-after-success", false, "monitor 任意账号成功后停止全部")
|
||||
accountStop = flag.Bool("account-stop", true, "monitor 单账号成功后停止该账号该奖品")
|
||||
at = flag.String("at", "", "定时开始时间,支持 RFC3339 或 2006-01-02 15:04:05")
|
||||
leadMS = flag.Int("lead", 2500, "monitor 相对 -at 提前启动毫秒")
|
||||
timeoutSec = flag.Int("timeout", 15, "单次请求超时秒数")
|
||||
transport = flag.String("transport", "wss", "传输层:wss/http,默认 wss")
|
||||
wssHost = flag.String("wss-host", "", "WSS host,留空则通过 launch.queryHttpDns 自动解析")
|
||||
prewarm = flag.Bool("prewarm", true, "monitor 开始前预热账号连接")
|
||||
directExchange = flag.Bool("direct-exchange", true, "monitor 已知 PID 时跳过列表直接兑换")
|
||||
listBefore = flag.Bool("list-before-exchange", false, "monitor 即使已知 PID 也先查询列表")
|
||||
shareList = flag.Bool("share-list", true, "monitor 多账号共享同一轮奖品列表")
|
||||
refreshSuccess = flag.Bool("refresh-after-success", true, "monitor 成功后异步刷新积分和记录")
|
||||
freqBackoffMS = flag.Int("freq-backoff", 300, "操作频繁后的账号退避毫秒")
|
||||
errorBackoffMS = flag.Int("error-backoff", 300, "请求异常后的账号退避毫秒")
|
||||
verbose = flag.Bool("v", false, "输出调试日志(同时打印到 stderr)")
|
||||
logDir = flag.String("log-dir", "", "日志目录,默认使用应用数据目录下的 logs")
|
||||
logLevel = flag.String("log-level", "info", "日志最低等级:debug/info/warn/error")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
initLogging(*logDir, *logLevel, *verbose)
|
||||
defer flushLogs()
|
||||
|
||||
if *sid <= 0 {
|
||||
exitErr(errors.New("必须提供有效 -sid"))
|
||||
}
|
||||
|
||||
cookies, err := loadCookies(*cookie, *cookieFile)
|
||||
if err != nil {
|
||||
exitErr(err)
|
||||
}
|
||||
accounts := make([]sniper.Account, 0, len(cookies))
|
||||
for _, ck := range cookies {
|
||||
uid := huya.ResolveUID(ck)
|
||||
if uid <= 0 {
|
||||
exitErr(errors.New("无法从 Cookie 解析 yyuid/udb_uid"))
|
||||
}
|
||||
accounts = append(accounts, sniper.Account{UID: uid, Cookie: ck})
|
||||
}
|
||||
|
||||
clientLogger := func(msg string) {
|
||||
logger.LogEvent(categoryNet, logger.LevelDebug, "%s", msg)
|
||||
if *verbose {
|
||||
fmt.Fprintln(os.Stderr, msg)
|
||||
}
|
||||
}
|
||||
client, closeClient, err := huya.NewActivityClient(*transport, *wssHost, time.Duration(*timeoutSec)*time.Second, clientLogger)
|
||||
if err != nil {
|
||||
exitErr(err)
|
||||
}
|
||||
defer closeClient()
|
||||
ctx := context.Background()
|
||||
|
||||
var startAt time.Time
|
||||
if *at != "" {
|
||||
when, err := parseTime(*at)
|
||||
if err != nil {
|
||||
exitErr(err)
|
||||
}
|
||||
startAt = when
|
||||
}
|
||||
|
||||
switch *cmd {
|
||||
case "list":
|
||||
waitForCommand(ctx, startAt)
|
||||
resp, err := client.GetActPrizeList(ctx, accounts[0].UID, accounts[0].Cookie, int32(*sid))
|
||||
if err != nil {
|
||||
exitErr(err)
|
||||
}
|
||||
logger.LogEvent(categoryCLI, logger.LevelInfo, "sid=%d 共%d项 类目=%s", *sid, len(resp.Prizes), resp.CategorySummary())
|
||||
key := strings.TrimSpace(*category)
|
||||
if *categoryOnly {
|
||||
if key == "" {
|
||||
exitErr(errors.New("-category-only 需要同时提供 -category"))
|
||||
}
|
||||
filtered := *resp
|
||||
filtered.Prizes = resp.FilterByCategory(key)
|
||||
logger.LogEvent(categoryCLI, logger.LevelInfo, "类目[%s]筛选后 %d/%d 项", key, len(filtered.Prizes), len(resp.Prizes))
|
||||
printJSON(filtered)
|
||||
return
|
||||
}
|
||||
printJSON(resp)
|
||||
case "score":
|
||||
waitForCommand(ctx, startAt)
|
||||
results := make([]map[string]any, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
resp, err := client.QueryUserScore(ctx, account.UID, account.Cookie, int32(*sid))
|
||||
results = append(results, map[string]any{
|
||||
"uid": account.UID,
|
||||
"resp": resp,
|
||||
"score": availableScore(resp),
|
||||
"error": errString(err),
|
||||
})
|
||||
}
|
||||
printJSON(results)
|
||||
case "records":
|
||||
waitForCommand(ctx, startAt)
|
||||
results := make([]map[string]any, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
resp, err := client.GetUserPrizeRecords(ctx, account.UID, account.Cookie, int32(*sid))
|
||||
results = append(results, map[string]any{
|
||||
"uid": account.UID,
|
||||
"resp": resp,
|
||||
"error": errString(err),
|
||||
})
|
||||
}
|
||||
printJSON(results)
|
||||
case "exchange":
|
||||
if *pid <= 0 {
|
||||
exitErr(errors.New("exchange 必须提供 -pid"))
|
||||
}
|
||||
waitForCommand(ctx, startAt)
|
||||
runExchange(ctx, client, accounts, int32(*sid), int32(*pid), *concurrency)
|
||||
case "monitor":
|
||||
targets := parseTargets(*pid, *pids, *name, *names, *autoSelect, *maxPrice, *minLeft)
|
||||
if len(targets) == 0 {
|
||||
exitErr(errors.New("monitor 必须提供 -pid 或 -name"))
|
||||
}
|
||||
runner := sniper.Runner{Client: client}
|
||||
var outMu sync.Mutex
|
||||
emit := func(result sniper.Result) {
|
||||
outMu.Lock()
|
||||
defer outMu.Unlock()
|
||||
_ = json.NewEncoder(os.Stdout).Encode(result)
|
||||
logger.LogAccountEvent(categoryMonitor, sniper.LogLevelForCategory(result.Category), strconv.FormatInt(result.UID, 10),
|
||||
"loop=%d action=%s category=%s msg=%s error=%s", result.Loop, result.Action, result.Category, result.Message, result.Error)
|
||||
}
|
||||
cfg := sniper.Config{
|
||||
SID: int32(*sid),
|
||||
Category: strings.TrimSpace(*category),
|
||||
Loops: *loops,
|
||||
Delay: time.Duration(*delayMS) * time.Millisecond,
|
||||
Concurrency: *concurrency,
|
||||
StopAfterSuccess: *stopAfterSuccess,
|
||||
StopAccountAfterSuccess: *accountStop,
|
||||
Prewarm: false,
|
||||
DirectExchange: *directExchange,
|
||||
ListBeforeExchange: *listBefore,
|
||||
SharePrizeList: *shareList,
|
||||
RefreshAfterSuccess: *refreshSuccess,
|
||||
TooFrequentBackoff: time.Duration(*freqBackoffMS) * time.Millisecond,
|
||||
ErrorBackoff: time.Duration(*errorBackoffMS) * time.Millisecond,
|
||||
}
|
||||
if *prewarm {
|
||||
if err := runner.Prewarm(ctx, accounts, cfg, emit); err != nil && !errors.Is(err, context.Canceled) {
|
||||
exitErr(err)
|
||||
}
|
||||
}
|
||||
waitForMonitor(ctx, startAt, time.Duration(*leadMS)*time.Millisecond)
|
||||
err := runner.RunTargets(ctx, accounts, targets, cfg, emit)
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
exitErr(err)
|
||||
}
|
||||
default:
|
||||
exitErr(fmt.Errorf("未知 -cmd: %s", *cmd))
|
||||
}
|
||||
}
|
||||
|
||||
func waitForCommand(ctx context.Context, startAt time.Time) {
|
||||
if !startAt.IsZero() {
|
||||
waitUntil(ctx, startAt)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForMonitor(ctx context.Context, startAt time.Time, lead time.Duration) {
|
||||
if startAt.IsZero() {
|
||||
return
|
||||
}
|
||||
when := startAt.Add(-lead)
|
||||
waitUntil(ctx, when)
|
||||
}
|
||||
|
||||
func runExchange(ctx context.Context, client huya.ActivityClient, accounts []sniper.Account, sid, pid int32, concurrency int) {
|
||||
if concurrency <= 0 {
|
||||
concurrency = 1
|
||||
}
|
||||
type item struct {
|
||||
UID int64 `json:"uid"`
|
||||
Resp *huya.ScoreExchangePrizeResp `json:"resp,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
results := make([]item, len(accounts))
|
||||
sem := make(chan struct{}, concurrency)
|
||||
var wg sync.WaitGroup
|
||||
for i, account := range accounts {
|
||||
i, account := i, account
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
resp, err := client.ScoreExchangePrize(ctx, account.UID, account.Cookie, sid, pid)
|
||||
results[i] = item{UID: account.UID, Resp: resp, Error: errString(err)}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
printJSON(results)
|
||||
}
|
||||
|
||||
func loadCookies(cookie, file string) ([]string, error) {
|
||||
var out []string
|
||||
if strings.TrimSpace(cookie) != "" {
|
||||
out = append(out, strings.TrimSpace(cookie))
|
||||
}
|
||||
if file != "" {
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
scanner := bufio.NewScanner(f)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, errors.New("必须提供 -cookie 或 -cookie-file")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func parseTargets(pid int, pids, name, names string, autoSelect bool, maxPrice, minLeft int64) []sniper.Target {
|
||||
targets := make([]sniper.Target, 0)
|
||||
name = strings.TrimSpace(name)
|
||||
if pid > 0 || name != "" {
|
||||
targets = append(targets, sniper.Target{PID: int32(pid), Name: name})
|
||||
}
|
||||
if autoSelect {
|
||||
targets = append(targets, sniper.Target{Auto: true})
|
||||
}
|
||||
for _, text := range splitList(pids) {
|
||||
value, err := strconv.Atoi(text)
|
||||
if err == nil && value > 0 {
|
||||
targets = append(targets, sniper.Target{PID: int32(value)})
|
||||
}
|
||||
}
|
||||
for _, text := range splitList(names) {
|
||||
if text == "auto" || text == "自动" || text == "自动选择" {
|
||||
targets = append(targets, sniper.Target{Auto: true})
|
||||
continue
|
||||
}
|
||||
targets = append(targets, sniper.Target{Name: text})
|
||||
}
|
||||
// 价格/库存过滤对所有目标统一生效。
|
||||
for i := range targets {
|
||||
targets[i].MaxPrice = maxPrice
|
||||
targets[i].MinLeft = minLeft
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
func splitList(text string) []string {
|
||||
replacer := strings.NewReplacer(",", ",", "\n", ",", "\t", ",", " ", ",")
|
||||
parts := strings.Split(replacer.Replace(text), ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
item := strings.TrimSpace(part)
|
||||
if item != "" {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func parseTime(text string) (time.Time, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return time.Time{}, errors.New("时间为空")
|
||||
}
|
||||
if ts, err := strconv.ParseInt(text, 10, 64); err == nil {
|
||||
return time.Unix(ts, 0), nil
|
||||
}
|
||||
for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05", "2006-01-02 15:04"} {
|
||||
if t, err := time.ParseInLocation(layout, text, time.Local); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("无法解析 -at 时间: %s", text)
|
||||
}
|
||||
|
||||
func waitUntil(ctx context.Context, when time.Time) {
|
||||
for {
|
||||
remaining := time.Until(when)
|
||||
if remaining <= 0 {
|
||||
return
|
||||
}
|
||||
timer := time.NewTimer(minDuration(remaining, 200*time.Millisecond))
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func printJSON(value any) {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(value); err != nil {
|
||||
exitErr(err)
|
||||
}
|
||||
}
|
||||
|
||||
func errString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func availableScore(resp *huya.GetUserScoreResp) int64 {
|
||||
if resp == nil {
|
||||
return 0
|
||||
}
|
||||
return resp.AvailableScore()
|
||||
}
|
||||
|
||||
// initLogging 初始化 CLI 日志:默认写入应用数据目录下的 logs,和 GUI 一样是
|
||||
// 结构化日志(带分类与账号标签),便于事后复盘。
|
||||
func initLogging(dir, level string, verbose bool) {
|
||||
if strings.TrimSpace(dir) == "" {
|
||||
dir = instance.DefaultLogDir()
|
||||
}
|
||||
logger.SetMinLevel(logger.LevelFromString(chooseLevel(level, verbose)))
|
||||
store := logger.NewStore(1000)
|
||||
closeFn, err := logger.Init(store, dir, "CLI", "cli", instance.DefaultDataDir())
|
||||
closeLogger = closeFn
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "日志文件不可用,仅保留在内存: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func chooseLevel(level string, verbose bool) string {
|
||||
if verbose {
|
||||
return logger.LevelDebug
|
||||
}
|
||||
return level
|
||||
}
|
||||
|
||||
// flushLogs 把异步日志队列刷盘;必须在 os.Exit 之前调用。
|
||||
func flushLogs() {
|
||||
if closeLogger != nil {
|
||||
closeLogger()
|
||||
closeLogger = nil
|
||||
}
|
||||
}
|
||||
|
||||
func exitErr(err error) {
|
||||
logger.LogEvent(categoryCLI, logger.LevelError, "%v", err)
|
||||
fmt.Fprintln(os.Stderr, "错误:", err)
|
||||
flushLogs()
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func minDuration(a, b time.Duration) time.Duration {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
# 抢购引擎优化计划(v0.4.0)
|
||||
|
||||
> 依据:2026-10-16 三台机器(pc-1 / pc-2 / pc-3)同一场活动(sid=2277,17:00 开抢)的真实日志复盘。
|
||||
> 参考:`/Users/yml/codes/dygou_go`(斗鱼)的调度设计,**只借鉴结论与参数形态,不照搬链路**(虎牙无锁单/支付,协议也不同)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 复盘数据(问题来源)
|
||||
|
||||
| 机器 | 账号 | 成功 | 成功率 | 兑换请求 | 火爆 | 频率限制 | 售罄 | 版本 |
|
||||
|---|---|---|---|---|---|---|---|---|
|
||||
| pc-1 | 152 | 85 | 56% | 1421 | 917 | 244 | 19 | 旧版(无汇总 / 无时钟校准 / 售罄即停) |
|
||||
| pc-2 | 10 | 7 | 70% | 81 | 51 | 1 | 0 | 新版(轮次窗口不足) |
|
||||
| pc-3 | 85 | 83 | 97.6% | 498 | — | 0 | 0 | 新版(目标未售罄) |
|
||||
| 合计 | 247 | 175 | 71% | 2000 | — | — | — | — |
|
||||
|
||||
关键事实:
|
||||
|
||||
1. 开抢窗口只有 **约 9 秒**(17:00:00.1 放量 → 17:00:08.2~09.4 售罄)。
|
||||
2. pc-1 的 **82%** 兑换请求(1161/1421)被服务端限流挡回(「活动太火爆了」+「领取频率限制」);同机同 IP 峰值约 122 req/s。
|
||||
3. `Delay` 默认 150ms 时,**账号越少,每秒轮次越多,越容易在开抢前把轮次烧光**:
|
||||
|
||||
| 实例 | 账号数 | 每轮耗时 | 20 轮覆盖 | 实际打进的开抢窗口 |
|
||||
|---|---|---|---|---|
|
||||
| pc-3 instance-4 | 1 | 155ms | 3.1s | **0 秒**(提前量 2.5s 吃掉全部预算 → 0 成功) |
|
||||
| pc-2 default | 3 | 178ms | 3.6s | ~1.0s |
|
||||
| pc-2 instance-3 | 3 | 170ms | 3.4s | ~1.2s |
|
||||
| pc-3 instance-3 | 22 | 586ms | 11.7s | 5.7s |
|
||||
| pc-1 各实例 | 30 | 830ms | 16.6s | 整窗口(但旧版售罄即停) |
|
||||
|
||||
4. pc-3 default 的账号 `1199662595042` **连续 13 次**返回 `webActUI.scoreExchangePrize 响应缺少 tRsp/tResp`,而同实例另外 28 个账号全部成功;日志里没有任何服务端线索。
|
||||
5. 服务端放行速率是稳定的"每秒 4~6 个"(pc-3 六秒曲线),不是瞬间批量 → **覆盖足够的窗口时长**比**更高瞬时并发**更有效。
|
||||
|
||||
## 2. 四个优化项(已确认全部实施)
|
||||
|
||||
| 编号 | 问题 | 现状证据 |
|
||||
|---|---|---|
|
||||
| P1 | 轮次预算被提前量吃掉,账号少的实例根本没打到开抢瞬间 | pc-3 i4 = 0 成功;pc-2 三实例开抢后 1~1.4s 收工 |
|
||||
| P2 | WUP/协议错误不可观测,且被混入普通失败 | 13 次 `缺少 tRsp/tResp` 只给了一句话,`iRet/status/payload` 全丢 |
|
||||
| P3 | 限流文案没分类,退避语义缺失 | `火爆`/`领取频率限制` 落到 `failed`,共用同一退避 |
|
||||
| P4 | 日志缺关键上下文 | `启动监控` 无 pid/名称;`账号未绑定` 与真失败同桶;无接口耗时统计 |
|
||||
|
||||
## 3. 参考方案(dygou_go)与适用边界
|
||||
|
||||
| dygou_go 做法 | 虎牙适用性 | 说明 |
|
||||
|---|---|---|
|
||||
| 窗口 `deadline` + `expired()`(75s)替代轮次 | ✅ 直接借鉴 | 虎牙实测窗口 ~9s,改为可配 `WindowSeconds`(建议默认 30s) |
|
||||
| 每账号独立循环,不做轮间同步 | ⚠️ 改造后借鉴 | 虎牙已有"请求级闸门 + 账号独立 loop",但外层仍按 loop 同步一轮 |
|
||||
| `dynamicAdvance = ErrorBound + RTT/2`,下限 50ms | ✅ 直接借鉴 | 替代固定 `LeadMS=2500` |
|
||||
| 触发前 3s 复校时钟(`resyncBeforeTrigger`) | ✅ 借鉴 | 虎牙已有 `OffsetHistory` 中位数平滑,缺"临近复校" |
|
||||
| 预热早于触发 2s(`warmupBeforeTrigger`) | ✅ 借鉴 | 改为"预热后静默等触发",不再让提前量循环白打 |
|
||||
| 首发错峰 `firstWaveSpread=300ms` / `step≤8ms` | ✅ 直接借鉴 | 缓解同机 152 账号同毫秒齐射 |
|
||||
| 退避阶梯 `retryIntervalFor(按已过时间分档)` + ×2 递增(≤×4) + 抖动,区间 [100ms,1.5s] | ✅ 直接借鉴 | 替代固定 300ms 退避 |
|
||||
| 售罄不终止、退避自动降速到秒级 | ✅ 已有 | huya-go 已在 0294606 实现,保留并加提示日志 |
|
||||
| 结局分类 success/rejected/throttled/terminal/expired | ✅ 借鉴 | 用于"窗口结束时"的每账号结局 |
|
||||
| 限流关键词表 `exchangeRateLimited`(火爆/频繁/繁忙/排队…) | ✅ 直接借鉴 | 补进 `classifyExchangeText` |
|
||||
| 请求统计(count/failed/avg/slowest/lastErr)+ 网络汇总行 | ✅ 借鉴 | 虎牙已有分类计数,补耗时与最后错误 |
|
||||
| 目标商品 id 打进日志(`productTargets`) | ✅ 直接借鉴 | 补 `启动监控` 的 pid + 名称 |
|
||||
| 抢购后积分核对(基线比对) | ✅ 借鉴 | 现有 `refresh_score` 可升级为"扣分=成功"二次确认 |
|
||||
| 锁单→支付、锁单 TTL/CSRF、支付阶梯、和平小店 | ❌ 不适用 | 虎牙是直接兑换、无锁单无支付 |
|
||||
| 斗鱼订单错误码表(1644400007 等) | ❌ 不适用 | 虎牙是 TAF/WUP,需按 `iRet / status / 文案` 三类信号自建 |
|
||||
|
||||
## 4. 现状代码坐标
|
||||
|
||||
| 位置 | 说明 |
|
||||
|---|---|
|
||||
| `internal/sniper/sniper.go:198` | `RunTargets` |
|
||||
| `internal/sniper/sniper.go:227` | `for loop := 1; loop <= cfg.Loops; loop++`(待替换的轮次模型) |
|
||||
| `internal/sniper/sniper.go:308` | `runAccountLoop` |
|
||||
| `internal/sniper/sniper.go:444 / 480` | `exchangeTarget` / `applyExchangeDecision`(退避决策) |
|
||||
| `internal/sniper/sniper.go:734` | `emitSummary` |
|
||||
| `internal/sniper/sniper.go:838` | `normalizeConfig`(默认 Delay 150ms / Backoff 300ms) |
|
||||
| `internal/sniper/sniper.go:996` | `classifyExchangeText`(文案分类) |
|
||||
| `internal/huya/wss_client.go:704` | `callRPC`(:715 丢诊断) |
|
||||
| `internal/huya/http_client.go:140 / 218` | `CallRPC`(:218 同样的丢诊断) |
|
||||
| `internal/wup/wup.go:97 / 229` | `Response`(有 `Message/Status/Context/NewData` 未用)、`ReadStruct` |
|
||||
| `internal/huya/timecal.go:98 / 145` | `AlignedTriggerTime` / `RunTimeCalibration`(已有中位数平滑) |
|
||||
| `internal/gui/app.go:502 / 522-540` | `启动监控` 日志 / 定时触发路径 |
|
||||
| ~~`cmd/huya-go/main.go:198 / 220`~~ | CLI `waitForMonitor` —— **CLI 已在 0.4.0 移除**(见文末「实施记录(续)」) |
|
||||
|
||||
## 5. 设计(四个工作包)
|
||||
|
||||
### WP1 窗口预算与首发时序(P1)
|
||||
|
||||
1.1 **终止条件:轮次 → 截止时间**
|
||||
- `Config` 新增:`WindowSeconds int`(默认 30)、`DeadlineAt time.Time`(内部)、`FirstWaveSpread / FirstWaveMaxStep`。
|
||||
- `RunTargets` 计算 `deadline := openAt + WindowSeconds`;循环条件改为 `!deadlineReached()`;`Loops > 0` 时仍作为上限(**向后兼容**:两者先到先止)。
|
||||
|
||||
1.2 **起跑阶段不消耗预算(消灭 pc-3 i4 的 0 成功)**
|
||||
- 两段式:阶段 A(预打探活)T-advance 起,每账号只发 1 次用于判断是否已开放;阶段 B(正式窗口)等 `openAt` 后才开始计预算,`deadline = openAt + WindowSeconds`。
|
||||
- 引擎自持 `openAt`(由 GUI 传入),不再把"等待"放在 `RunTargets` 之外。
|
||||
|
||||
1.3 **首发错峰**
|
||||
- `runState.firstWaveSlot()`:第 0 个账号立即发,其余 `slot × step`;`step = min(spread/(n-1), maxStep)`,`spread=300ms`、`maxStep=8ms`(152 账号 → 2ms/步,总铺开 300ms)。
|
||||
|
||||
1.4 **触发时序统一(引擎与 GUI 共用一份实现)**
|
||||
- 新增 `internal/sniper/timing.go`:`PlanTrigger(target, calibration, fallbackLead) Plan{WarmupAt, ResyncAt, TriggerAt, Advance, WindowEnd}`。
|
||||
- GUI(`internal/gui/app.go` 的 `StartMonitor`)改为调用同一函数:预热 T-2s、复校 T-3s、触发 T-advance、窗口结束 openAt+WindowSeconds。
|
||||
- `advance = max(ErrorBound + RTT/2, 50ms)`;`LeadMS > 0` 时覆盖动态值(兼容旧配置)。
|
||||
|
||||
1.5 **退避阶梯**
|
||||
- 新增 `retryDelay(elapsed, failStreak)`:基准按"已过时间"分档(默认 0-2s→150ms、2-5s→400ms、>5s→900ms,可配 `RetryStages`),连续失败 ×2(上限 ×4),抖动 0-25%,区间 [100ms, 1500ms]。
|
||||
- 退避等待被 deadline 裁剪(`sleepUntil(deadline, d)`);窗口结束立即收尾,不再产生窗口外的无效失败。
|
||||
|
||||
### WP2 WUP/协议错误可观测性(P2)
|
||||
|
||||
2.1 `wup.Response` 新增 `Diagnose()`:`iRet=%d servant=%s func=%s status=%v context=%v keys=%v payload=%dB`(value 截断、key 排序,保证日志稳定)。
|
||||
2.2 `wss_client.callRPC`(:715)与 `http_client.CallRPC`(:218):tRsp 缺失时错误串带上 `resp.Diagnose()`。
|
||||
2.3 新增 debug 级原始帧日志:`cmd=`、帧长度、前 32 字节 HEX(仅在日志等级为 debug 时输出)。
|
||||
2.4 新增分类 `CategoryProtocol = "protocol"`(解码失败、缺 tRsp、帧异常)→ 日志等级 error、独立计数。
|
||||
2.5 新增分类 `CategorySessionLost = "session_lost"`("账号未绑定"/"登录态"/"token"):瞬时错误照常重试,连续 ≥3 次才升级为账号级终止并打 warn。
|
||||
2.6 单测:构造 `iRet≠0 且无 tRsp` 的响应 → 断言错误串含 iRet/status/keys;"账号未绑定" → 断言新分类。
|
||||
|
||||
### WP3 限流分类与退避(P3)
|
||||
|
||||
3.1 `classifyExchangeText` 关键词扩充(借 dygou 的关键词表)
|
||||
- 归入 `too_frequent`:`火爆`、`频繁`、`稍后重试`、`太频繁`、`限流`、`繁忙`、`人多`、`排队`、`手慢`、`点击太快`、`请求过多`、`行为异常`。
|
||||
- 判定顺序固定:`未开放 → 已抢完/库存 → 货币不足/已兑换 → 限流 → 兜底`,避免"稍后重试"吃掉"售罄"。
|
||||
|
||||
3.2 汇总口径扩充:`RunSummary` 增 `Throttled / SoldOut / SessionLost / Protocol`;汇总行形如
|
||||
`任务结束: 窗口=30.0s 账号=29 成功=28 限流=123(67%) 售罄=19 协议错误=13 耗时=9.1s`
|
||||
|
||||
3.3 退避:`too_frequent` 走 WP1.5 的阶梯,并支持"连续 N 次限流后该账号基础间隔 ×2"(N 默认 3)。
|
||||
|
||||
3.4 (可选,默认关)**全局自适应降速**:最近 1s 限流占比 > 60% 时,把基础间隔与并发按 1.5 倍衰减,10s 窗口后恢复。开关 `AdaptiveThrottle`,用于缓解 pc-1 那种 122 req/s → 82% 限流的同 IP 风暴。
|
||||
|
||||
3.5 终态修正:限流/火爆/未绑定一律**不终止**(现状已如此,补测试固化)。
|
||||
|
||||
### WP4 日志与复盘(P4)
|
||||
|
||||
4.1 `启动监控` 带目标明细:
|
||||
`启动监控: sid=2277 类目=不限 targets=1 目标=13437(冠军之刃) accounts=29 窗口=30s 提前=动态≈120ms 首发错峰=300ms`
|
||||
4.2 每账号一行结局(任务结束时):`账号=1234 结局=限流中结束 请求=12 最后=活动太火爆了,请稍后重试`
|
||||
4.3 结局分布带原因:`结局 sold_out ×19(窗口结束仍售罄)`
|
||||
4.4 接口统计行:`网络: scoreExchangePrize ×183 失败136 平均=412ms 最慢=2.1s 最后错误=…`
|
||||
4.5 触发日志补全:`触发=… 复校=… 窗口结束=…`
|
||||
|
||||
## 6. 兼容性与风险
|
||||
|
||||
- **向后兼容**:`Loops > 0` 仍生效(作为上限);`LeadMS > 0` 覆盖动态提前量;新字段全部有默认值,GUI 都可关闭新行为。
|
||||
- **风险 1**:窗口拉长 → 请求量上升。缓解:退避阶梯 + deadline 裁剪 + 可选自适应降速;`WindowSeconds` 可调。
|
||||
- **风险 2**:首发错峰牺牲首波瞬时性。缓解:总铺开仅 300ms,而实测窗口有 9s 余量;第 0 个账号仍立即发。
|
||||
- **风险 3**:动态提前量下限 50ms 可能压不住慢网络。缓解:`ErrorBound + RTT/2` 已含往返补偿,且保留"预打探活"。
|
||||
- **风险 4**:新增分类影响 GUI 配色/筛选。缓解:`LogLevelForCategory` 补映射(protocol→error,session_lost→warn),前端按 level 上色即可。
|
||||
- **风险 5**:`classifyExchangeText` 顺序调整可能改变既有用例结论。缓解:先补"售罄/货币不足优先于限流"的回归测试再改。
|
||||
|
||||
## 7. 验收标准(DoD)
|
||||
|
||||
- `go test ./...` 全绿;新增 ≥12 个用例(窗口预算、首发错峰、退避阶梯、分类、诊断串、临近复校)。
|
||||
- 关键回归不破:售罄继续探测、同奖品重复兑换去重、成功后异步刷新、`StopAfterSuccess`。
|
||||
- `go build ./...` 与 `wails build`(或 `-debug -nopackage`)通过;版本号升到 `0.4.0`。
|
||||
- 日志验收(可用假 client 跑模拟):一次运行必须输出「窗口参数行 / 目标明细行 / 每账号结局行 / 汇总行 / 接口统计行」。
|
||||
- 反向验收:账号数 = 1、`Loops=1`、窗口 30s 时,日志必须显示"有效请求覆盖到窗口结束",不再出现"开抢前收工"。
|
||||
|
||||
## 8. 里程碑与改动清单
|
||||
|
||||
| 里程碑 | 内容 | 主要文件 | 产出 |
|
||||
|---|---|---|---|
|
||||
| M1 | WP2 可观测性(低风险、独立、立即可用于复盘) | `internal/wup/wup.go`、`internal/huya/wss_client.go`、`internal/huya/http_client.go`、`internal/sniper/sniper.go`(+分类)、测试 | 新分类 + 诊断串 |
|
||||
| M2 | WP3 限流分类与退避 | `internal/sniper/sniper.go`、`sniper_test.go`、`internal/gui/app.go` | 退避阶梯 + 汇总口径 |
|
||||
| M3 | WP1 窗口预算与首发时序 | `internal/sniper/sniper.go`、新增 `internal/sniper/timing.go`、`internal/gui/app.go`、`internal/huya/timecal.go` | 窗口调度 |
|
||||
| M4 | WP4 日志补齐 + 版本/文档 | `internal/gui/app.go`、`internal/logger`、`README.md`、`internal/version` | 可复盘日志 |
|
||||
|
||||
顺序理由:先把"看不清"变成"看得清"(M1/M2),再动调度核心(M3),最后收尾(M4)。
|
||||
|
||||
## 9. 待确认参数
|
||||
|
||||
| 参数 | 建议值 | 说明 |
|
||||
|---|---|---|
|
||||
| `WindowSeconds` | 30s | 实测售罄 9s;30s 覆盖「库存回流/补货」 |
|
||||
| 首发错峰总量 / 单步上限 | 300ms / 8ms | 152 账号 → step 2ms |
|
||||
| 退避区间 | [100ms, 1500ms] | 超过 1.5s 的等待可能正好错过回流库存 |
|
||||
| 「账号未绑定」升级阈值 | 连续 3 次 | 实测同一账号下一轮即可成功(瞬时) |
|
||||
| 自适应降速(WP3.4) | 默认开 | 由用户确认:默认打开,GUI 可关 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 实施记录(v0.4.0,2026-10-16)
|
||||
|
||||
四个工作包已全部落地,`go test ./...`、`go vet`、`wails build`、前端 `npm run typecheck && npm run build` 均通过。
|
||||
|
||||
### 已实现
|
||||
|
||||
| 工作包 | 落地位置 |
|
||||
|---|---|
|
||||
| WP1 窗口预算 | `internal/sniper/sniper.go`(`Config.OpenAt/WindowSeconds/StartAhead`、`runState.configureWindow/windowExpired/windowStart/needsPrefire`、`RunTargets` 重写)、`internal/sniper/timing.go`(`PlanTrigger`)、`internal/gui/app.go` |
|
||||
| WP1 首发错峰 | `runState.takeFirstWaveDelay` + `runAccountLoop` 首次尝试等待 |
|
||||
| WP1 退避阶梯 | `runState.retryDelay / scheduleRetry / stageMultiplier / streakMultiplier / bumpFailStreak` |
|
||||
| WP2 可观测性 | `internal/wup/wup.go`(`Diagnose`、`HexHead`)、`internal/huya/diagnose.go`(`ErrProtocolResponse`、`protocolResponseError`)、`internal/huya/wss_client.go`、`internal/huya/http_client.go` |
|
||||
| WP2 新分类 | `CategoryProtocol`、`CategorySessionLost` + `LogLevelForCategory` / `CategoryLabel` |
|
||||
| WP3 限流分类 | `classifyExchangeText` 关键词表 + 固定判定顺序 |
|
||||
| WP3 汇总口径 | `RunSummary.Throttled`(经 `Outcomes[too_frequent]` 统计)、`RequestStats`、`AccountOutcomes` |
|
||||
| WP3 自适应降速 | `throttleGovernor` + `runState.observeThrottle/throttleFactor` |
|
||||
| WP4 日志 | `logRunSummary`(GUI)、`sniper.TargetSummary`、`App.logWindowPlan`、`waitFor` |
|
||||
| 测试 | `internal/sniper/optimization_test.go`(15 个新用例 + 下文 11.4 再补 4 个)、`internal/wup/wup_test.go`(诊断串 + 原始帧前缀)、`internal/huya/diagnose_test.go`(协议错误判定)、前端 `tsc --noEmit` |
|
||||
|
||||
### 与原计划的三处偏差(有实测依据)
|
||||
|
||||
1. **自适应降速的触发信号改为「无进展」而不是「限流占比 > 60%」**。
|
||||
原计划按限流占比判定,但实测数据显示 pc-3(成功率 97.6%)也有 67% 请求被限流、pc-1 是 82% —— 用占比阈值会把正常运行的机器一起拖慢。改为「连续 ≥12 个请求且 ≥800ms 拿不到任何业务响应」,命中后按 1.5 倍逐级降速(上限 4 倍),有进展立刻回退。
|
||||
2. **退避阶梯不引入 `RetryStages` 配置项**,改为在既有 `ErrorBackoff/TooFrequentBackoff` 基础上乘「时间档位 + 连续失败档位」:既不新增配置面,又避免「连续售罄探测」这类正常等待被放大(售罄/未开放档位更保守)。
|
||||
3. **窗口模式下 `Loops` 语义调整**:`OpenAt` 非零时 `Loops<=0` 表示跑到窗口结束(GUI 默认留空),`Loops>0` 仍作为单个账号的轮次上限;非窗口模式(测试与直接调用)保持原来的「默认 1 轮」语义,避免老行为回归。
|
||||
|
||||
### 顺带修掉的两个小问题
|
||||
|
||||
- 同一「账号 + 奖品」的「已兑换过,跳过重复兑换」提示改为只报一次:窗口模式下每轮都会命中,不限制会刷满整个窗口(请求数不变)。
|
||||
- 会话失效计数在任何非会话失效结局后清零,避免历史计数把偶发抖动累积成「连续失效」。
|
||||
|
||||
---
|
||||
|
||||
## 11. 实施记录(续):每账号独立循环 + 共享列表 TTL + 移除 CLI(v0.4.0,2026-10-16)
|
||||
|
||||
三机复盘后用户追加两条要求:**每个账号独立抢购**(不再一批一批同步)、**移除 CLI 只保留 GUI**。
|
||||
|
||||
### 11.1 调度:批次同步 → 每账号独立循环
|
||||
|
||||
**旧实现**:`RunTargets` 外层是 `for loop := 1..Loops`,每轮把所有账号并发跑一遍再 `wg.Wait()` 等齐,然后按 `nextWaveDelay` 等一个共享间隔进入下一轮。慢账号(一次 2s 的请求)会把所有账号钉在这一轮的终点上,账号少的实例尤其吃亏(pc-3 instance-4 = 0 成功)。
|
||||
|
||||
**新实现**(`internal/sniper/sniper.go`):
|
||||
|
||||
| 旧 | 新 |
|
||||
|---|---|
|
||||
| `for loop` + `runWave(loop)` + 每轮 `wg.Wait()` 同步 | 每个账号一个 goroutine 跑 `runAccountLoop`,各自 `for round := 1; ;` 循环 |
|
||||
| `nextWaveDelay` 批次间隔 | 账号自己的 `cfg.Delay`(`clipToDeadline` 裁剪到窗口结束) |
|
||||
| `runAccountLoop(..., loop, sharedList)` 是一轮的尝试体 | 拆成 `runAccountLoop`(循环)+ `runAccountRound`(一轮尝试体) |
|
||||
| 局部 `loopsRun` 记轮次 | `runState.noteRound/maxRound`(取所有账号的最大轮次) |
|
||||
| 每轮开头只判断 `allDone()` | `allDone()` + `windowExpired()` + `accountFinished(uid, len(targets))` |
|
||||
|
||||
退出条件(每个账号独立判断):任务取消 → 显式轮次上限(`Loops > 0`)→ 全局目标终止(售罄/下架,`targetDone`)→ 窗口结束 → 本账号所有目标已完成。
|
||||
|
||||
**保留的批次语义**:开抢前的「预打一轮」(`runWave(1)`)仍是全账号一波并发,用于探活与验证通道;只有正式窗口改成独立循环。
|
||||
|
||||
**验证**:新增 `TestRunTargetsPerAccountLoopsAreIndependent` —— 账号 1 的第一个兑换请求被阻塞时,账号 2 必须已经独立跑完 ≥3 轮(旧实现下账号 2 会卡在第二轮起点)。
|
||||
|
||||
### 11.2 共享列表:每轮一个新快照 → TTL + 单飞缓存
|
||||
|
||||
`SharePrizeList` 原来的语义是「每一轮所有账号共用同一份快照」,在批次调度下等价于每轮查 1 次列表。改成独立循环后「一轮」不再有全局含义,于是把共享口径改为**按时间的快照缓存**(`runState.sharedListOnce`):
|
||||
|
||||
- 锁内优先复用 1 秒 TTL 内的成功快照;没有可用快照时**单飞**——只有一个账号真正发请求,其余账号等它完成后复用结果。
|
||||
- **只缓存成功结果**:失败不写缓存,否则一次抖动会让所有账号一起拿着错误快照失败。
|
||||
- `sharedListTTL = 1000ms`:单次查询约 100ms,单账号节奏是 `cfg.Delay`(默认 150~300ms)。1 秒既能让同一波账号复用一份快照(pc-1 的 152 个账号从每轮 152 次查询降到 1 次),又能及时看到库存变化(实测库存会回流,快照不能太旧)。
|
||||
- 关闭 `SharePrizeList` 时保持原样:各查各的,不做任何缓存。
|
||||
|
||||
**验证**:新增 `TestRunTargetsSharedListTTLSingleFlight` —— 2 账号 × 3 轮,列表请求数必须为 1(只做单飞、无 TTL 时是 3~6 次)。
|
||||
|
||||
### 11.3 移除 CLI(只保留 GUI)
|
||||
|
||||
CLI 与 GUI 是两套并行入口(`prepareMonitor` / `logRunSummary` / 参数解析各一份),改动要同步两处,老计划里甚至专门列了「GUI 与 CLI 需保持一致」这一条。既然日常只用 GUI,直接删掉:
|
||||
|
||||
- 删除 `cmd/huya-go/`;`internal/sniper` 的 `Runner`/`Config` 完全由 GUI 复用,删除 CLI 不影响引擎。
|
||||
- `internal/gui/app.go` 的 `StartMonitor` 成为唯一触发路径(时间校准 → 窗口计划 → `RunTargets`)。
|
||||
- `README.md`:删掉 CLI 构建/示例/参数表,改为「设置项说明」,并把「GUI 与 CLI 一致」等表述收敛为 GUI。
|
||||
|
||||
### 11.4 本轮新增测试(4 个,全部通过)
|
||||
|
||||
| 用例 | 覆盖 |
|
||||
|---|---|
|
||||
| `TestRunTargetsPerAccountLoopsAreIndependent` | 慢账号不阻塞其他账号 |
|
||||
| `TestRunTargetsSharedListTTLSingleFlight` | 共享列表 TTL + 单飞只查 1 次 |
|
||||
| `TestRunStateClipToDeadline` | 等待被裁剪到窗口结束(含已过期与非窗口模式) |
|
||||
| `TestRunStateAccountFinishedAndRoundTracking` | `accountFinished`(含全局目标终止)与 `maxRound` |
|
||||
|
||||
+354
-40
@@ -29,6 +29,7 @@ import {
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Save,
|
||||
ShieldCheck,
|
||||
ShoppingCart,
|
||||
Square,
|
||||
Settings,
|
||||
@@ -36,6 +37,7 @@ import {
|
||||
Zap,
|
||||
} from 'lucide-react'
|
||||
import {
|
||||
CheckCookies,
|
||||
DefaultConfig,
|
||||
Exchange,
|
||||
GetInstanceInfo,
|
||||
@@ -58,6 +60,9 @@ import { ClipboardGetText, ClipboardSetText, EventsOn } from '../wailsjs/runtime
|
||||
const configStorageBase = 'huya-go.gui.config.v2'
|
||||
const cookieStorageBase = 'huya-go.gui.cookies.v1'
|
||||
const prizeCacheStorageBase = 'huya-go.gui.prizes.v1'
|
||||
const leadDefaultMigrationBase = 'huya-go.gui.lead-default.v1'
|
||||
// 旧版本默认把提前量写成 2500ms,与现在的动态提前设计冲突;只迁移一次。
|
||||
const legacyDefaultLeadMs = 2500
|
||||
|
||||
// 界面本地存储保留的日志上限,与后端的增量拉取配合使用。
|
||||
const maxClientLogs = 1000
|
||||
@@ -97,9 +102,12 @@ type UiConfig = {
|
||||
minLeft: number
|
||||
cookieText: string
|
||||
selectedAccountLines: number[]
|
||||
// loops 是轮次上限:0(留空)表示按窗口运行到窗口结束。
|
||||
loops: number
|
||||
delayMs: number
|
||||
concurrency: number
|
||||
// windowSeconds 是抢购窗口秒数(窗口模式下跑到「开抢+窗口」才收工)。
|
||||
windowSeconds: number
|
||||
stopAfterSuccess: boolean
|
||||
stopAccountAfterSuccess: boolean
|
||||
prewarm: boolean
|
||||
@@ -108,10 +116,27 @@ type UiConfig = {
|
||||
autoSelect: boolean
|
||||
refreshAfterSuccess: boolean
|
||||
leadMs: number
|
||||
// timeSync 表示定时前用 pingSignal 校准服务端时间,并把 startAt 视为服务端时间。
|
||||
timeSync: boolean
|
||||
frequentBackoffMs: number
|
||||
errorBackoffMs: number
|
||||
timeoutSec: number
|
||||
startAt: string
|
||||
// adaptiveThrottle 是「全局自适应降速」开关(表单用正语义)。
|
||||
adaptiveThrottle: boolean
|
||||
// disableAdaptiveThrottle 只发给后端(后端零值=开启,所以用反语义字段),不落本地存储。
|
||||
disableAdaptiveThrottle: boolean
|
||||
}
|
||||
|
||||
type CookieCheckStatus = 'valid' | 'expired' | 'unknown' | 'invalid'
|
||||
|
||||
type CookieCheckResult = {
|
||||
line: number
|
||||
uid: number
|
||||
status: CookieCheckStatus
|
||||
message?: string
|
||||
statusCode?: number
|
||||
checkedAt: number
|
||||
}
|
||||
|
||||
type AccountPreview = {
|
||||
@@ -119,6 +144,10 @@ type AccountPreview = {
|
||||
uid: number
|
||||
valid: boolean
|
||||
error?: string
|
||||
// checkStatus 是服务端登录态检查结果;valid 仅表示本地能解析出 uid。
|
||||
checkStatus?: CookieCheckStatus
|
||||
checkMessage?: string
|
||||
checkedAt?: number
|
||||
}
|
||||
|
||||
type CookieEntry = {
|
||||
@@ -127,6 +156,9 @@ type CookieEntry = {
|
||||
uid: number
|
||||
valid: boolean
|
||||
error?: string
|
||||
checkStatus?: CookieCheckStatus
|
||||
checkMessage?: string
|
||||
checkedAt?: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
@@ -299,7 +331,7 @@ function exchangeOrderID(exchange?: ExchangeResp): string {
|
||||
return exchange?.order_id || exchange?.orderId || ''
|
||||
}
|
||||
|
||||
type SavedConfig = Omit<UiConfig, 'cookieText' | 'selectedAccountLines'>
|
||||
type SavedConfig = Omit<UiConfig, 'cookieText' | 'selectedAccountLines' | 'disableAdaptiveThrottle'>
|
||||
|
||||
type ScheduleCountdown = {
|
||||
targetAt: number
|
||||
@@ -464,15 +496,55 @@ function categoryTag(category?: string): ReactNode {
|
||||
condition: { color: 'geekblue', label: '条件' },
|
||||
failed: { color: 'warning', label: '失败' },
|
||||
error: { color: 'error', label: '异常' },
|
||||
// protocol 是回包结构异常(缺 tRsp/tResp),单独归类便于排查服务端错误信封。
|
||||
protocol: { color: 'error', label: '协议异常' },
|
||||
// session_lost 是「账号未绑定」这类瞬时会话失效,通常下一轮就能恢复。
|
||||
session_lost: { color: 'volcano', label: '会话失效' },
|
||||
}
|
||||
if (!category) return <Tag>待处理</Tag>
|
||||
const item = map[category] || { color: 'default', label: category }
|
||||
return <Tag color={item.color}>{item.label}</Tag>
|
||||
}
|
||||
|
||||
function normalizeCookieCheckStatus(value: unknown): CookieCheckStatus | undefined {
|
||||
const status = String(value || '').trim()
|
||||
if (status === 'valid' || status === 'expired' || status === 'unknown' || status === 'invalid') {
|
||||
return status
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function isCookieCheckUnusable(status?: CookieCheckStatus): boolean {
|
||||
return status === 'expired' || status === 'unknown' || status === 'invalid'
|
||||
}
|
||||
|
||||
function cookieCheckTag(status?: CookieCheckStatus, message?: string): ReactNode {
|
||||
const config: Record<CookieCheckStatus | 'unchecked', { color: string; label: string }> = {
|
||||
valid: { color: 'success', label: '可用' },
|
||||
expired: { color: 'error', label: '失效' },
|
||||
unknown: { color: 'error', label: '失效' },
|
||||
invalid: { color: 'error', label: '无效' },
|
||||
unchecked: { color: 'default', label: '未检查' },
|
||||
}
|
||||
const item = config[status || 'unchecked']
|
||||
const tag = <Tag color={item.color}>{item.label}</Tag>
|
||||
return message ? <Tooltip title={message}>{tag}</Tooltip> : tag
|
||||
}
|
||||
|
||||
function readSavedConfig(): Partial<SavedConfig> {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(scopedKey(configStorageBase)) || '{}') as Partial<SavedConfig>
|
||||
const configKey = scopedKey(configStorageBase)
|
||||
const saved = JSON.parse(localStorage.getItem(configKey) || '{}') as Partial<SavedConfig>
|
||||
const migrationKey = scopedKey(leadDefaultMigrationBase)
|
||||
if (!localStorage.getItem(migrationKey)) {
|
||||
if (Number(saved.leadMs || 0) === legacyDefaultLeadMs) {
|
||||
saved.leadMs = 0
|
||||
// 迁移必须立即落盘,否则下一次 readSavedConfig 又会读回旧值。
|
||||
localStorage.setItem(configKey, JSON.stringify(saved))
|
||||
}
|
||||
localStorage.setItem(migrationKey, '1')
|
||||
}
|
||||
return saved
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
@@ -492,6 +564,9 @@ function readSavedCookies(): CookieEntry[] {
|
||||
uid: Number(item.uid || 0),
|
||||
valid: Boolean(item.valid),
|
||||
error: item.error,
|
||||
checkStatus: normalizeCookieCheckStatus(item.checkStatus),
|
||||
checkMessage: String(item.checkMessage || '').trim() || undefined,
|
||||
checkedAt: Number(item.checkedAt || 0) || undefined,
|
||||
updatedAt: Number(item.updatedAt || Date.now()),
|
||||
}))
|
||||
.filter((item) => item.text)
|
||||
@@ -581,9 +656,10 @@ function pickConfig(values: Partial<UiConfig>): UiConfig {
|
||||
minLeft: Number(values.minLeft || 0),
|
||||
cookieText: values.cookieText || '',
|
||||
selectedAccountLines: values.selectedAccountLines || [],
|
||||
loops: Number(values.loops || 1),
|
||||
loops: Number(values.loops || 0),
|
||||
delayMs: Number(values.delayMs || 150),
|
||||
concurrency: Number(values.concurrency || 1),
|
||||
windowSeconds: Number(values.windowSeconds || 30),
|
||||
stopAfterSuccess: Boolean(values.stopAfterSuccess),
|
||||
stopAccountAfterSuccess: values.stopAccountAfterSuccess !== false,
|
||||
prewarm: values.prewarm !== false,
|
||||
@@ -592,10 +668,13 @@ function pickConfig(values: Partial<UiConfig>): UiConfig {
|
||||
autoSelect: Boolean(values.autoSelect),
|
||||
refreshAfterSuccess: values.refreshAfterSuccess !== false,
|
||||
leadMs: Number(values.leadMs || 0),
|
||||
timeSync: values.timeSync !== false,
|
||||
frequentBackoffMs: Number(values.frequentBackoffMs || 300),
|
||||
errorBackoffMs: Number(values.errorBackoffMs || 300),
|
||||
timeoutSec: Number(values.timeoutSec || 15),
|
||||
startAt: values.startAt || '',
|
||||
adaptiveThrottle: values.adaptiveThrottle !== false,
|
||||
disableAdaptiveThrottle: values.adaptiveThrottle === false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,11 +768,23 @@ export default function Dashboard() {
|
||||
}
|
||||
})
|
||||
setCookieEntries(enriched)
|
||||
setAccounts(previews || [])
|
||||
setSelectedAccountLines((previews || []).filter((item) => item.valid).map((item) => item.line))
|
||||
const enrichedPreviews = (previews || []).map((preview) => {
|
||||
const entry = enriched[preview.line - 1]
|
||||
return {
|
||||
...preview,
|
||||
checkStatus: entry?.checkStatus,
|
||||
checkMessage: entry?.checkMessage,
|
||||
checkedAt: entry?.checkedAt,
|
||||
}
|
||||
})
|
||||
setAccounts(enrichedPreviews)
|
||||
const selectableLines = enrichedPreviews
|
||||
.filter((item) => item.valid && !isCookieCheckUnusable(item.checkStatus))
|
||||
.map((item) => item.line)
|
||||
setSelectedAccountLines(selectableLines)
|
||||
if (persist) writeSavedCookies(enriched)
|
||||
if (refreshLatest && enriched.some((item) => item.valid)) {
|
||||
window.setTimeout(() => queryPrizes(true), 0)
|
||||
if (refreshLatest && selectableLines.length > 0) {
|
||||
window.setTimeout(() => queryPrizes(true, selectableLines), 0)
|
||||
}
|
||||
return enriched
|
||||
}
|
||||
@@ -781,7 +872,22 @@ export default function Dashboard() {
|
||||
writeSavedConfigPatch({ startAt: String(form.getFieldValue('startAt') || '') })
|
||||
}, [configLoaded, form, watchedStartAt])
|
||||
|
||||
const validAccounts = useMemo(() => accounts.filter((item) => item.valid), [accounts])
|
||||
const validAccounts = useMemo(
|
||||
() => accounts.filter((item) => item.valid && !isCookieCheckUnusable(item.checkStatus)),
|
||||
[accounts],
|
||||
)
|
||||
const cookieCheckStats = useMemo(() => {
|
||||
const stats = { valid: 0, expired: 0, unknown: 0, invalid: 0, unchecked: 0 }
|
||||
cookieEntries.forEach((entry) => {
|
||||
if (entry.checkStatus === 'valid') stats.valid += 1
|
||||
else if (entry.checkStatus === 'expired') stats.expired += 1
|
||||
else if (entry.checkStatus === 'unknown') stats.unknown += 1
|
||||
else if (entry.checkStatus === 'invalid') stats.invalid += 1
|
||||
else stats.unchecked += 1
|
||||
})
|
||||
return stats
|
||||
}, [cookieEntries])
|
||||
const failedCookieCount = cookieCheckStats.expired + cookieCheckStats.unknown + cookieCheckStats.invalid
|
||||
const importedCookieCount = useMemo(
|
||||
() => normalizeCookieText(watchedCookieText || '').split('\n').filter(Boolean).length,
|
||||
[watchedCookieText],
|
||||
@@ -854,7 +960,7 @@ export default function Dashboard() {
|
||||
const errorCount = useMemo(
|
||||
() =>
|
||||
results.filter((item) =>
|
||||
['error', 'failed', 'not_enough', 'off_shelf', 'sold_out', 'condition'].includes(
|
||||
['error', 'failed', 'not_enough', 'off_shelf', 'sold_out', 'condition', 'protocol'].includes(
|
||||
item.category || '',
|
||||
),
|
||||
).length,
|
||||
@@ -901,10 +1007,10 @@ export default function Dashboard() {
|
||||
[logs, logFilter],
|
||||
)
|
||||
|
||||
const config = () => ({
|
||||
const config = (selectedLines: Key[] = selectedAccountLines) => ({
|
||||
...pickConfig(form.getFieldsValue(true)),
|
||||
category: activeCategory,
|
||||
selectedAccountLines: selectedAccountLines.map(Number).filter((line) => line > 0),
|
||||
selectedAccountLines: selectedLines.map(Number).filter((line) => line > 0),
|
||||
})
|
||||
|
||||
const runAction = async <T,>(
|
||||
@@ -1004,7 +1110,16 @@ export default function Dashboard() {
|
||||
if (editingCookie) {
|
||||
const text = normalizedText.split('\n')[0]
|
||||
const nextEntries = cookieEntries.map((entry) =>
|
||||
entry.id === editingCookie.id ? { ...entry, text, updatedAt: Date.now() } : entry,
|
||||
entry.id === editingCookie.id
|
||||
? {
|
||||
...entry,
|
||||
text,
|
||||
checkStatus: undefined,
|
||||
checkMessage: undefined,
|
||||
checkedAt: undefined,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
: entry,
|
||||
)
|
||||
await applyCookieEntries(nextEntries, true, true)
|
||||
message.success('CK 已更新')
|
||||
@@ -1047,13 +1162,110 @@ export default function Dashboard() {
|
||||
message.success('已重新载入本地 CK')
|
||||
}
|
||||
|
||||
function queryPrizes(quiet = false) {
|
||||
// 检查走服务端 getUserScore;失效结果连续确认 3 次,避免偶发「账号未绑定」误判。
|
||||
const checkCookies = async () => {
|
||||
if (running) {
|
||||
message.warning('抢购运行中,请先停止再检查 CK')
|
||||
return
|
||||
}
|
||||
if (cookieEntries.length === 0) {
|
||||
message.warning('没有可检查的 CK')
|
||||
return
|
||||
}
|
||||
setLoading('cookie-check')
|
||||
try {
|
||||
const snapshot = cookieEntries
|
||||
const results = (await CheckCookies(config())) as CookieCheckResult[]
|
||||
const byLine = new Map<number, CookieCheckResult>()
|
||||
const byUID = new Map<number, CookieCheckResult>()
|
||||
results.forEach((item) => {
|
||||
byLine.set(Number(item.line || 0), item)
|
||||
if (Number(item.uid || 0) > 0) byUID.set(Number(item.uid), item)
|
||||
})
|
||||
|
||||
const nextEntries = snapshot.map((entry, index) => {
|
||||
const result = byLine.get(index + 1) || (entry.uid > 0 ? byUID.get(entry.uid) : undefined)
|
||||
if (!result) return entry
|
||||
return {
|
||||
...entry,
|
||||
uid: Number(result.uid || entry.uid || 0),
|
||||
checkStatus: normalizeCookieCheckStatus(result.status),
|
||||
checkMessage: result.status === 'valid' ? '' : String(result.message || '').trim(),
|
||||
checkedAt: Number(result.checkedAt || Date.now()),
|
||||
}
|
||||
})
|
||||
|
||||
const stats = { valid: 0, expired: 0, unknown: 0, invalid: 0 }
|
||||
nextEntries.forEach((entry) => {
|
||||
if (entry.checkStatus === 'valid') stats.valid += 1
|
||||
else if (entry.checkStatus === 'expired') stats.expired += 1
|
||||
else if (entry.checkStatus === 'unknown') stats.unknown += 1
|
||||
else if (entry.checkStatus === 'invalid') stats.invalid += 1
|
||||
})
|
||||
const failed = stats.expired + stats.unknown + stats.invalid
|
||||
|
||||
setCookieEntries(nextEntries)
|
||||
writeSavedCookies(nextEntries)
|
||||
setAccounts((prev) =>
|
||||
prev.map((account) => {
|
||||
const result = byLine.get(account.line) || (account.uid > 0 ? byUID.get(account.uid) : undefined)
|
||||
if (!result) return account
|
||||
return {
|
||||
...account,
|
||||
checkStatus: normalizeCookieCheckStatus(result.status),
|
||||
checkMessage: result.status === 'valid' ? '' : String(result.message || '').trim(),
|
||||
checkedAt: Number(result.checkedAt || Date.now()),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const failedLines = new Set(
|
||||
nextEntries
|
||||
.map((entry, index) => (isCookieCheckUnusable(entry.checkStatus) ? index + 1 : 0))
|
||||
.filter((line) => line > 0),
|
||||
)
|
||||
setSelectedAccountLines((prev) => prev.filter((line) => !failedLines.has(Number(line))))
|
||||
|
||||
const summary = `检查完成:可用 ${stats.valid},失效 ${failed}`
|
||||
if (failed > 0) {
|
||||
message.warning(summary)
|
||||
} else {
|
||||
message.success(summary)
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
message.error(`检查 CK 失败: ${String(err)}`)
|
||||
} finally {
|
||||
setLoading('')
|
||||
}
|
||||
}
|
||||
|
||||
const clearExpiredCookies = () => {
|
||||
if (failedCookieCount === 0) return
|
||||
modal.confirm({
|
||||
title: '清理失效 CK',
|
||||
content: `确认删除 ${failedCookieCount} 条失效 CK?未检查的 CK 会保留。`,
|
||||
okText: '清理',
|
||||
cancelText: '取消',
|
||||
okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
const remaining = cookieEntries.filter((entry) => !isCookieCheckUnusable(entry.checkStatus))
|
||||
await applyCookieEntries(remaining, true, false)
|
||||
message.success(`已清理 ${failedCookieCount} 条失效 CK`)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function queryPrizes(quiet = false, selectedLines: Key[] = selectedAccountLines) {
|
||||
if (!String(form.getFieldValue('cookieText') || '').trim()) {
|
||||
if (!quiet) message.warning('Cookie 不能为空')
|
||||
return
|
||||
}
|
||||
if (selectedLines.length === 0) {
|
||||
if (!quiet) message.warning('请先选择账号')
|
||||
return
|
||||
}
|
||||
setLoading('list')
|
||||
ListPrizes(config())
|
||||
ListPrizes(config(selectedLines))
|
||||
.then((data) => {
|
||||
const result = data as {
|
||||
prizes?: PrizeInfo[]
|
||||
@@ -1131,6 +1343,7 @@ export default function Dashboard() {
|
||||
loops: values.loops,
|
||||
delayMs: values.delayMs,
|
||||
concurrency: values.concurrency,
|
||||
windowSeconds: values.windowSeconds,
|
||||
stopAfterSuccess: values.stopAfterSuccess,
|
||||
stopAccountAfterSuccess: values.stopAccountAfterSuccess,
|
||||
prewarm: values.prewarm,
|
||||
@@ -1139,10 +1352,12 @@ export default function Dashboard() {
|
||||
autoSelect: values.autoSelect,
|
||||
refreshAfterSuccess: values.refreshAfterSuccess,
|
||||
leadMs: values.leadMs,
|
||||
timeSync: values.timeSync,
|
||||
frequentBackoffMs: values.frequentBackoffMs,
|
||||
errorBackoffMs: values.errorBackoffMs,
|
||||
timeoutSec: values.timeoutSec,
|
||||
startAt: values.startAt,
|
||||
adaptiveThrottle: values.adaptiveThrottle,
|
||||
}
|
||||
localStorage.setItem(scopedKey(configStorageBase), JSON.stringify(saved))
|
||||
message.success('已保存')
|
||||
@@ -1167,6 +1382,10 @@ export default function Dashboard() {
|
||||
|
||||
const startMonitor = (scheduled: boolean) => {
|
||||
const values = config()
|
||||
if (values.selectedAccountLines.length === 0) {
|
||||
message.warning('请先选择账号')
|
||||
return undefined
|
||||
}
|
||||
const countdown = scheduled ? buildScheduleCountdown(values.startAt, values.leadMs, now) : null
|
||||
if (scheduled && !countdown) {
|
||||
message.warning('请先填写定时目标时间(HH:mm:ss)')
|
||||
@@ -1185,6 +1404,10 @@ export default function Dashboard() {
|
||||
|
||||
const directExchange = () => {
|
||||
const values = config()
|
||||
if (values.selectedAccountLines.length === 0) {
|
||||
message.warning('请先选择账号')
|
||||
return undefined
|
||||
}
|
||||
if (Number(values.pid || 0) <= 0) {
|
||||
message.warning('请先在左侧商品列表中选择要兑换的商品')
|
||||
return undefined
|
||||
@@ -1242,14 +1465,29 @@ export default function Dashboard() {
|
||||
render: (_, row) => (
|
||||
<div>
|
||||
<strong>{row.uid || `第${row.line}行`}</strong>
|
||||
<div className="muted">{row.valid ? '已加入任务' : row.error || '未选择'}</div>
|
||||
<div className="muted">
|
||||
{isCookieCheckUnusable(row.checkStatus)
|
||||
? row.checkMessage || 'CK 已失效'
|
||||
: row.valid
|
||||
? row.checkStatus === 'valid'
|
||||
? 'CK 可用'
|
||||
: '已加入任务'
|
||||
: row.error || '未选择'}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '凭据',
|
||||
width: 90,
|
||||
render: (_, row) => (row.valid ? <Tag color="green">已加载</Tag> : <Tag>无效</Tag>),
|
||||
width: 110,
|
||||
render: (_, row) =>
|
||||
row.checkStatus ? (
|
||||
cookieCheckTag(row.checkStatus, row.checkMessage)
|
||||
) : row.valid ? (
|
||||
<Tag color="green">已加载</Tag>
|
||||
) : (
|
||||
<Tag>无效</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '商品',
|
||||
@@ -1348,18 +1586,37 @@ export default function Dashboard() {
|
||||
() => [
|
||||
{
|
||||
title: '账号',
|
||||
width: 150,
|
||||
width: 140,
|
||||
render: (_, row) => (
|
||||
<div>
|
||||
<strong>{row.uid || '-'}</strong>
|
||||
<div className="muted">{row.valid ? '有效 CK' : row.error || '待校验'}</div>
|
||||
<div className="muted">
|
||||
{isCookieCheckUnusable(row.checkStatus) ? 'CK 已失效' : row.valid ? '可解析 UID' : row.error || '待校验'}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
width: 86,
|
||||
render: (_, row) => (row.valid ? <Tag color="green">有效</Tag> : <Tag color="error">无效</Tag>),
|
||||
title: '格式',
|
||||
width: 78,
|
||||
render: (_, row) => (row.valid ? <Tag color="green">有效</Tag> : <Tag color="default">无效</Tag>),
|
||||
},
|
||||
{
|
||||
title: 'CK 状态',
|
||||
width: 190,
|
||||
render: (_, row) => (
|
||||
<div>
|
||||
{cookieCheckTag(row.checkStatus, row.checkMessage)}
|
||||
{row.checkStatus && row.checkStatus !== 'valid' && row.checkMessage ? (
|
||||
<div className="muted ck-check-message" title={row.checkMessage}>
|
||||
{row.checkMessage}
|
||||
</div>
|
||||
) : null}
|
||||
{row.checkedAt ? (
|
||||
<div className="muted">检查于 {new Date(row.checkedAt).toLocaleString('zh-CN', { hour12: false })}</div>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'CK',
|
||||
@@ -1575,7 +1832,7 @@ export default function Dashboard() {
|
||||
block
|
||||
icon={<RefreshCw size={16} />}
|
||||
loading={loading === 'list'}
|
||||
disabled={validAccounts.length === 0}
|
||||
disabled={selectedAccountCount === 0}
|
||||
onClick={() => queryPrizes()}
|
||||
>
|
||||
用 CK 刷新商品
|
||||
@@ -1699,7 +1956,7 @@ export default function Dashboard() {
|
||||
type="primary"
|
||||
icon={<ShoppingCart size={16} />}
|
||||
loading={loading === 'monitor'}
|
||||
disabled={running}
|
||||
disabled={running || selectedAccountCount === 0}
|
||||
onClick={() => startMonitor(false)}
|
||||
>
|
||||
立即抢购
|
||||
@@ -1709,7 +1966,7 @@ export default function Dashboard() {
|
||||
type="primary"
|
||||
icon={<Play size={16} />}
|
||||
loading={loading === 'monitor'}
|
||||
disabled={running}
|
||||
disabled={running || selectedAccountCount === 0}
|
||||
onClick={() => startMonitor(true)}
|
||||
>
|
||||
开启定时
|
||||
@@ -1717,7 +1974,7 @@ export default function Dashboard() {
|
||||
<Button
|
||||
icon={<Zap size={16} />}
|
||||
loading={loading === 'exchange'}
|
||||
disabled={running || validAccounts.length === 0}
|
||||
disabled={running || selectedAccountCount === 0}
|
||||
onClick={directExchange}
|
||||
>
|
||||
直接兑换
|
||||
@@ -1732,22 +1989,42 @@ export default function Dashboard() {
|
||||
<Button
|
||||
icon={<RefreshCw size={16} />}
|
||||
loading={loading === 'score'}
|
||||
onClick={() =>
|
||||
runAction('score', () => QueryScores(config()), (data) =>
|
||||
disabled={selectedAccountCount === 0}
|
||||
onClick={() => {
|
||||
const values = config()
|
||||
if (values.selectedAccountLines.length === 0) {
|
||||
message.warning('请先选择账号')
|
||||
return
|
||||
}
|
||||
runAction('score', () => QueryScores(values), (data) =>
|
||||
setScores((data || []) as ScoreResult[]),
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
查询积分
|
||||
</Button>
|
||||
<Button
|
||||
icon={<ShieldCheck size={16} />}
|
||||
loading={loading === 'cookie-check'}
|
||||
disabled={running || cookieEntries.length === 0}
|
||||
onClick={checkCookies}
|
||||
>
|
||||
CK 有效性
|
||||
</Button>
|
||||
<Button
|
||||
icon={<ClipboardList size={16} />}
|
||||
loading={loading === 'records'}
|
||||
onClick={() =>
|
||||
runAction('records', () => GetRecords(config()), (data) =>
|
||||
disabled={selectedAccountCount === 0}
|
||||
onClick={() => {
|
||||
const values = config()
|
||||
if (values.selectedAccountLines.length === 0) {
|
||||
message.warning('请先选择账号')
|
||||
return
|
||||
}
|
||||
runAction('records', () => GetRecords(values), (data) =>
|
||||
setRecords((data || []) as RecordResult[]),
|
||||
)
|
||||
}
|
||||
}}
|
||||
>
|
||||
兑换记录
|
||||
</Button>
|
||||
@@ -1795,7 +2072,9 @@ export default function Dashboard() {
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedAccountLines,
|
||||
onChange: setSelectedAccountLines,
|
||||
getCheckboxProps: (row) => ({ disabled: !row.valid }),
|
||||
getCheckboxProps: (row) => ({
|
||||
disabled: !row.valid || isCookieCheckUnusable(row.checkStatus),
|
||||
}),
|
||||
}}
|
||||
columns={accountColumns}
|
||||
dataSource={accounts}
|
||||
@@ -1828,7 +2107,15 @@ export default function Dashboard() {
|
||||
<Modal
|
||||
title="CK 管理"
|
||||
open={cookieManagerOpen}
|
||||
width={980}
|
||||
width="min(1080px, calc(100vw - 48px))"
|
||||
style={{ maxWidth: 'calc(100vw - 24px)' }}
|
||||
styles={{
|
||||
body: {
|
||||
maxHeight: 'calc(100vh - 180px)',
|
||||
overflowY: 'auto',
|
||||
overflowX: 'hidden',
|
||||
},
|
||||
}}
|
||||
onCancel={() => setCookieManagerOpen(false)}
|
||||
footer={null}
|
||||
>
|
||||
@@ -1848,10 +2135,28 @@ export default function Dashboard() {
|
||||
<Button icon={<RefreshCw size={16} />} onClick={reloadSavedCookies}>
|
||||
重新载入
|
||||
</Button>
|
||||
<Button
|
||||
icon={<ShieldCheck size={16} />}
|
||||
loading={loading === 'cookie-check'}
|
||||
disabled={running || cookieEntries.length === 0}
|
||||
onClick={checkCookies}
|
||||
>
|
||||
检查 CK 有效性
|
||||
</Button>
|
||||
</Space>
|
||||
<Space wrap>
|
||||
<Tag>{cookieEntries.length} 条 CK</Tag>
|
||||
<Tag color="green">{validAccounts.length} 个有效</Tag>
|
||||
<Tag color="green">{cookieCheckStats.valid} 可用</Tag>
|
||||
{failedCookieCount > 0 ? <Tag color="error">{failedCookieCount} 失效</Tag> : null}
|
||||
{cookieCheckStats.unchecked > 0 ? <Tag>{cookieCheckStats.unchecked} 未检查</Tag> : null}
|
||||
<Button
|
||||
danger
|
||||
icon={<Trash2 size={16} />}
|
||||
disabled={failedCookieCount === 0}
|
||||
onClick={clearExpiredCookies}
|
||||
>
|
||||
清理失效
|
||||
</Button>
|
||||
<Button
|
||||
danger
|
||||
icon={<Trash2 size={16} />}
|
||||
@@ -1868,7 +2173,7 @@ export default function Dashboard() {
|
||||
columns={cookieColumns}
|
||||
dataSource={cookieEntries}
|
||||
pagination={{ pageSize: 8, showSizeChanger: false }}
|
||||
scroll={{ x: 900, y: 430 }}
|
||||
scroll={{ x: 1000, y: 430 }}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -1962,8 +2267,11 @@ export default function Dashboard() {
|
||||
<Form.Item name="minLeft" label="最少库存">
|
||||
<InputNumber min={0} />
|
||||
</Form.Item>
|
||||
<Form.Item name="loops" label="次数">
|
||||
<InputNumber min={1} max={9999} />
|
||||
<Form.Item name="loops" label="次数上限" tooltip="留空或 0 = 按窗口运行到窗口结束;填了就作为轮次上限">
|
||||
<InputNumber min={0} max={9999} placeholder="0=按窗口" />
|
||||
</Form.Item>
|
||||
<Form.Item name="windowSeconds" label="窗口秒" tooltip="窗口模式下跑到「开抢 + 窗口秒数」才收工;开抢后约 9 秒内库存就会见底,默认 30 秒留足库存回流余量">
|
||||
<InputNumber min={1} max={600} addonAfter="s" />
|
||||
</Form.Item>
|
||||
<Form.Item name="delayMs" label="延时">
|
||||
<InputNumber min={10} max={60000} addonAfter="ms" />
|
||||
@@ -1971,8 +2279,8 @@ export default function Dashboard() {
|
||||
<Form.Item name="concurrency" label="线程">
|
||||
<InputNumber min={1} max={100} />
|
||||
</Form.Item>
|
||||
<Form.Item name="leadMs" label="提前">
|
||||
<InputNumber min={0} max={10000} addonAfter="ms" />
|
||||
<Form.Item name="leadMs" label="提前" tooltip="留空或 0 = 按服务端时钟校准误差动态计算(通常几十毫秒);填了就用固定提前量">
|
||||
<InputNumber min={0} max={10000} addonAfter="ms" placeholder="0=动态" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
<div className="settings-switch-grid">
|
||||
@@ -1994,6 +2302,12 @@ export default function Dashboard() {
|
||||
<Form.Item name="refreshAfterSuccess" label="成功刷新" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item name="timeSync" label="时间校准" valuePropName="checked" tooltip="定时前用 pingSignal 校准服务端时间,按钟差对齐触发时刻">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
<Form.Item name="adaptiveThrottle" label="自适应降速" valuePropName="checked" tooltip="连续十几个请求都拿不到业务响应时整体降速,缓解同机同 IP 的限流风暴">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
+26
-1
@@ -502,24 +502,49 @@ body {
|
||||
.ck-manager {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ck-manager-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.ck-manager-tools > .ant-space {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.ck-manager-tools > .ant-space:last-child {
|
||||
margin-left: auto;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.ck-manager .ant-table-wrapper,
|
||||
.ck-manager .ant-spin-nested-loading,
|
||||
.ck-manager .ant-spin-container {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ck-text-preview {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
color: #344054;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ck-check-message {
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
word-break: break-all;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
}
|
||||
|
||||
.settings-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
||||
Vendored
+2
@@ -3,6 +3,8 @@
|
||||
import {gui} from '../models';
|
||||
import {logger} from '../models';
|
||||
|
||||
export function CheckCookies(arg1:gui.Config):Promise<Array<gui.CookieCheckResult>>;
|
||||
|
||||
export function DefaultConfig():Promise<gui.Config>;
|
||||
|
||||
export function Exchange(arg1:gui.Config):Promise<Array<gui.ExchangeResult>>;
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
export function CheckCookies(arg1) {
|
||||
return window['go']['gui']['App']['CheckCookies'](arg1);
|
||||
}
|
||||
|
||||
export function DefaultConfig() {
|
||||
return window['go']['gui']['App']['DefaultConfig']();
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
export namespace gui {
|
||||
|
||||
|
||||
export class AccountPreview {
|
||||
line: number;
|
||||
uid: number;
|
||||
valid: boolean;
|
||||
error?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new AccountPreview(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.line = source["line"];
|
||||
@@ -41,15 +41,18 @@ export namespace gui {
|
||||
autoSelect: boolean;
|
||||
refreshAfterSuccess: boolean;
|
||||
leadMs: number;
|
||||
timeSync: boolean;
|
||||
frequentBackoffMs: number;
|
||||
errorBackoffMs: number;
|
||||
timeoutSec: number;
|
||||
startAt: string;
|
||||
|
||||
windowSeconds: number;
|
||||
disableAdaptiveThrottle: boolean;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Config(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.transport = source["transport"];
|
||||
@@ -74,10 +77,35 @@ export namespace gui {
|
||||
this.autoSelect = source["autoSelect"];
|
||||
this.refreshAfterSuccess = source["refreshAfterSuccess"];
|
||||
this.leadMs = source["leadMs"];
|
||||
this.timeSync = source["timeSync"];
|
||||
this.frequentBackoffMs = source["frequentBackoffMs"];
|
||||
this.errorBackoffMs = source["errorBackoffMs"];
|
||||
this.timeoutSec = source["timeoutSec"];
|
||||
this.startAt = source["startAt"];
|
||||
this.windowSeconds = source["windowSeconds"];
|
||||
this.disableAdaptiveThrottle = source["disableAdaptiveThrottle"];
|
||||
}
|
||||
}
|
||||
export class CookieCheckResult {
|
||||
line: number;
|
||||
uid: number;
|
||||
status: string;
|
||||
message?: string;
|
||||
statusCode?: number;
|
||||
checkedAt: number;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new CookieCheckResult(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.line = source["line"];
|
||||
this.uid = source["uid"];
|
||||
this.status = source["status"];
|
||||
this.message = source["message"];
|
||||
this.statusCode = source["statusCode"];
|
||||
this.checkedAt = source["checkedAt"];
|
||||
}
|
||||
}
|
||||
export class ExchangeResult {
|
||||
@@ -86,11 +114,11 @@ export namespace gui {
|
||||
category?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ExchangeResult(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.uid = source["uid"];
|
||||
@@ -99,7 +127,7 @@ export namespace gui {
|
||||
this.message = source["message"];
|
||||
this.error = source["error"];
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -124,11 +152,11 @@ export namespace gui {
|
||||
dataDir: string;
|
||||
logDir: string;
|
||||
logFile: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new InstanceInfo(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.name = source["name"];
|
||||
@@ -144,11 +172,11 @@ export namespace gui {
|
||||
dir: string;
|
||||
dropped: number;
|
||||
count: number;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new LogStats(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.level = source["level"];
|
||||
@@ -166,11 +194,11 @@ export namespace gui {
|
||||
categories: huya.PrizeTag[];
|
||||
categoryStats: huya.CategoryStat[];
|
||||
raw?: huya.GetActPrizeListResp;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PrizeListResult(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.uid = source["uid"];
|
||||
@@ -181,7 +209,7 @@ export namespace gui {
|
||||
this.categoryStats = this.convertValues(source["categoryStats"], huya.CategoryStat);
|
||||
this.raw = this.convertValues(source["raw"], huya.GetActPrizeListResp);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -205,11 +233,11 @@ export namespace gui {
|
||||
records: huya.UserPrizeInfo[];
|
||||
resp?: huya.GetUserPrizeRecordsResp;
|
||||
error?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new RecordResult(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.uid = source["uid"];
|
||||
@@ -217,7 +245,7 @@ export namespace gui {
|
||||
this.resp = this.convertValues(source["resp"], huya.GetUserPrizeRecordsResp);
|
||||
this.error = source["error"];
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -241,11 +269,11 @@ export namespace gui {
|
||||
score: number;
|
||||
resp?: huya.GetUserScoreResp;
|
||||
error?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ScoreResult(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.uid = source["uid"];
|
||||
@@ -253,7 +281,7 @@ export namespace gui {
|
||||
this.resp = this.convertValues(source["resp"], huya.GetUserScoreResp);
|
||||
this.error = source["error"];
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -276,18 +304,18 @@ export namespace gui {
|
||||
}
|
||||
|
||||
export namespace huya {
|
||||
|
||||
|
||||
export class ActPreCondition {
|
||||
condition_type: number;
|
||||
condition_params?: Record<string, string>;
|
||||
tip?: string;
|
||||
jump_url?: string;
|
||||
button_desc?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ActPreCondition(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.condition_type = source["condition_type"];
|
||||
@@ -303,11 +331,11 @@ export namespace huya {
|
||||
count: number;
|
||||
left: number;
|
||||
total: number;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new CategoryStat(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
@@ -321,11 +349,11 @@ export namespace huya {
|
||||
pid: number;
|
||||
exchange_score: number;
|
||||
desc: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ExchangeInfo(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.pid = source["pid"];
|
||||
@@ -337,11 +365,11 @@ export namespace huya {
|
||||
id: number;
|
||||
name: string;
|
||||
weight: number;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PrizeTag(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
@@ -372,11 +400,11 @@ export namespace huya {
|
||||
end_time?: number;
|
||||
daily_start?: string;
|
||||
daily_end?: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PrizeInfo(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
@@ -409,11 +437,11 @@ export namespace huya {
|
||||
prizes: PrizeInfo[];
|
||||
module_id: number;
|
||||
tags: PrizeTag[];
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GetActPrizeListResp(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.status = source["status"];
|
||||
@@ -422,7 +450,7 @@ export namespace huya {
|
||||
this.module_id = source["module_id"];
|
||||
this.tags = this.convertValues(source["tags"], PrizeTag);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -460,11 +488,11 @@ export namespace huya {
|
||||
item_id?: number;
|
||||
ext?: Record<string, string>;
|
||||
exchange_date?: number;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new UserPrizeInfo(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
@@ -491,18 +519,18 @@ export namespace huya {
|
||||
status: number;
|
||||
msg: string;
|
||||
records: UserPrizeInfo[];
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GetUserPrizeRecordsResp(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.status = source["status"];
|
||||
this.msg = source["msg"];
|
||||
this.records = this.convertValues(source["records"], UserPrizeInfo);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -530,11 +558,11 @@ export namespace huya {
|
||||
new_used_score: number;
|
||||
score: number;
|
||||
is_open_exchange_tip: number;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new GetUserScoreResp(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.status = source["status"];
|
||||
@@ -547,19 +575,19 @@ export namespace huya {
|
||||
this.is_open_exchange_tip = source["is_open_exchange_tip"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
export class ScoreExchangePrizeResp {
|
||||
status: number;
|
||||
msg: string;
|
||||
order_id?: string;
|
||||
exchange_info: ExchangeInfo;
|
||||
act_pre_condition: ActPreCondition;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new ScoreExchangePrizeResp(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.status = source["status"];
|
||||
@@ -568,7 +596,7 @@ export namespace huya {
|
||||
this.exchange_info = this.convertValues(source["exchange_info"], ExchangeInfo);
|
||||
this.act_pre_condition = this.convertValues(source["act_pre_condition"], ActPreCondition);
|
||||
}
|
||||
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
@@ -591,7 +619,7 @@ export namespace huya {
|
||||
}
|
||||
|
||||
export namespace logger {
|
||||
|
||||
|
||||
export class Entry {
|
||||
id: number;
|
||||
time: string;
|
||||
@@ -599,11 +627,11 @@ export namespace logger {
|
||||
category: string;
|
||||
account: string;
|
||||
message: string;
|
||||
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Entry(source);
|
||||
}
|
||||
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.id = source["id"];
|
||||
|
||||
Executable → Regular
Executable → Regular
+198
-45
@@ -77,10 +77,18 @@ type Config struct {
|
||||
AutoSelect bool `json:"autoSelect"`
|
||||
RefreshAfterSuccess bool `json:"refreshAfterSuccess"`
|
||||
LeadMS int `json:"leadMs"`
|
||||
FrequentBackoffMS int `json:"frequentBackoffMs"`
|
||||
ErrorBackoffMS int `json:"errorBackoffMs"`
|
||||
TimeoutSec int `json:"timeoutSec"`
|
||||
StartAt string `json:"startAt"`
|
||||
// TimeSync 表示定时抢购前先用 pingSignal 校准服务端时间,并把 StartAt 当服务端时间对齐。
|
||||
TimeSync bool `json:"timeSync"`
|
||||
FrequentBackoffMS int `json:"frequentBackoffMs"`
|
||||
ErrorBackoffMS int `json:"errorBackoffMs"`
|
||||
TimeoutSec int `json:"timeoutSec"`
|
||||
StartAt string `json:"startAt"`
|
||||
// WindowSeconds 是抢购窗口长度(秒):窗口模式下跑到「开抢 + 窗口」才收工,
|
||||
// 账号少时也不会像旧实现那样在开抢前把轮次烧光。<=0 时取默认 30 秒。
|
||||
WindowSeconds int `json:"windowSeconds"`
|
||||
// DisableAdaptiveThrottle 关闭全局自适应降速(默认开启,故用反向字段):
|
||||
// 连续十几个请求都拿不到业务响应时整体降速,缓解同机同 IP 的限流风暴。
|
||||
DisableAdaptiveThrottle bool `json:"disableAdaptiveThrottle"`
|
||||
}
|
||||
|
||||
type AccountPreview struct {
|
||||
@@ -307,7 +315,8 @@ func (a *App) DefaultConfig() Config {
|
||||
SharePrizeList: true,
|
||||
AutoSelect: false,
|
||||
RefreshAfterSuccess: true,
|
||||
LeadMS: 2500,
|
||||
LeadMS: 0,
|
||||
TimeSync: true,
|
||||
FrequentBackoffMS: 300,
|
||||
ErrorBackoffMS: 300,
|
||||
TimeoutSec: 15,
|
||||
@@ -496,57 +505,199 @@ func (a *App) StartMonitor(cfg Config) error {
|
||||
}
|
||||
|
||||
a.emitState(true, "运行中")
|
||||
a.addLog("info", "启动监控: sid=%d 类目=%s targets=%d accounts=%d prewarm=%v direct=%v", cfg.SID, sniper.CategoryText(cfg.Category), len(targets), len(accounts), cfg.Prewarm, cfg.DirectExchange)
|
||||
a.addLog("info", "启动监控: sid=%d 类目=%s targets=%d 目标=%s accounts=%d prewarm=%v direct=%v 窗口=%s 自适应降速=%v",
|
||||
cfg.SID, sniper.CategoryText(cfg.Category), len(targets), sniper.TargetSummary(targets), len(accounts),
|
||||
cfg.Prewarm, cfg.DirectExchange, sniper.WindowDuration(cfg.WindowSeconds), !cfg.DisableAdaptiveThrottle)
|
||||
|
||||
go func() {
|
||||
defer closeClient()
|
||||
defer a.finishMonitor("已停止")
|
||||
|
||||
runner := sniper.Runner{Client: client}
|
||||
runner := sniper.Runner{Client: client, OnSummary: a.logRunSummary}
|
||||
emit := func(result sniper.Result) {
|
||||
a.emit(eventMonitorResult, result)
|
||||
a.logAccount(categoryMonitor, sniper.LogLevelForCategory(result.Category), strconv.FormatInt(result.UID, 10),
|
||||
"loop=%d action=%s category=%s msg=%s error=%s", result.Loop, result.Action, result.Category, result.Message, result.Error)
|
||||
}
|
||||
runnerCfg := sniper.Config{
|
||||
SID: cfg.SID,
|
||||
Category: cfg.Category,
|
||||
Loops: cfg.Loops,
|
||||
Delay: time.Duration(cfg.DelayMS) * time.Millisecond,
|
||||
Concurrency: cfg.Concurrency,
|
||||
StopAfterSuccess: cfg.StopAfterSuccess,
|
||||
StopAccountAfterSuccess: cfg.StopAccountAfterSuccess,
|
||||
Prewarm: false,
|
||||
DirectExchange: cfg.DirectExchange,
|
||||
SharePrizeList: cfg.SharePrizeList,
|
||||
RefreshAfterSuccess: cfg.RefreshAfterSuccess,
|
||||
TooFrequentBackoff: time.Duration(cfg.FrequentBackoffMS) * time.Millisecond,
|
||||
ErrorBackoff: time.Duration(cfg.ErrorBackoffMS) * time.Millisecond,
|
||||
runnerCfg := runnerConfig(cfg)
|
||||
|
||||
// 立即抢购:预热完就进入窗口,窗口从当前时刻起算。
|
||||
if startAt.IsZero() {
|
||||
if cfg.Prewarm {
|
||||
a.addLog("info", "开始预热连接: accounts=%d", len(accounts))
|
||||
if err := runner.Prewarm(ctx, accounts, runnerCfg, emit); err != nil {
|
||||
a.addLog("error", "连接预热异常: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
runnerCfg.OpenAt = time.Now()
|
||||
a.logWindowPlan(runnerCfg.OpenAt, sniper.WindowDuration(cfg.WindowSeconds))
|
||||
a.runMonitor(ctx, runner, accounts, targets, runnerCfg, emit)
|
||||
return
|
||||
}
|
||||
|
||||
// 定时抢购:临近复校 → 预热 → 触发,全部按服务端时钟对齐。
|
||||
// 早启动的旧实现会先预热再干等几十分钟,连接和时钟都可能已经漂了。
|
||||
lead := time.Duration(cfg.LeadMS) * time.Millisecond
|
||||
window := sniper.WindowDuration(cfg.WindowSeconds)
|
||||
plan := sniper.PlanTrigger(startAt, huya.TimeCalibration{}, lead, window)
|
||||
|
||||
// 先复校时钟(开抢前 3s),再预热连接(开抢前 2s),最后等触发。
|
||||
// 顺序不能反:复校比预热更早,早做完才能把偏移用在这之后的所有时刻上。
|
||||
if cfg.TimeSync {
|
||||
if err := a.waitFor(ctx, plan.ResyncAt, "复校"); err != nil {
|
||||
return
|
||||
}
|
||||
calibration, calErr := huya.TryCalibrateServerTime(ctx, client, accounts[0].UID, accounts[0].Cookie, huya.DefaultTimeCalibrationRounds)
|
||||
if calErr != nil {
|
||||
a.addLog("warn", "时间校准失败,按本机时钟触发: %v", calErr)
|
||||
} else {
|
||||
plan = sniper.PlanTrigger(startAt, calibration, lead, window)
|
||||
a.addLog("info", "时间校准完成: %s", calibration.Summary())
|
||||
}
|
||||
}
|
||||
if cfg.Prewarm {
|
||||
a.addLog("info", "开始预热连接: accounts=%d", len(accounts))
|
||||
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
|
||||
}
|
||||
}
|
||||
if !startAt.IsZero() {
|
||||
when := startAt.Add(-time.Duration(cfg.LeadMS) * time.Millisecond)
|
||||
a.addLog("info", "等待定时开始: %s 提前=%dms", when.Format("2006-01-02 15:04:05.000"), cfg.LeadMS)
|
||||
if err := waitUntil(ctx, when); err != nil {
|
||||
a.addLog("info", "定时等待已取消")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err := runner.RunTargets(ctx, accounts, targets, runnerCfg, emit)
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
a.addLog("error", "监控结束异常: %v", err)
|
||||
runnerCfg.OpenAt = plan.OpenAt
|
||||
a.addLog("info", "等待定时开始: 触发=%s 开抢=%s 窗口结束=%s 提前=%dms 首发错峰=%dms",
|
||||
plan.TriggerAt.Format("2006-01-02 15:04:05.000"),
|
||||
plan.OpenAt.Format("2006-01-02 15:04:05.000"),
|
||||
plan.WindowEnd.Format("2006-01-02 15:04:05.000"),
|
||||
plan.Advance.Milliseconds(),
|
||||
sniper.DefaultFirstWaveSpread.Milliseconds())
|
||||
if err := waitUntil(ctx, plan.TriggerAt); err != nil {
|
||||
a.addLog("info", "定时等待已取消")
|
||||
return
|
||||
}
|
||||
a.runMonitor(ctx, runner, accounts, targets, runnerCfg, emit)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMonitor 执行抢购并把异常写进日志。
|
||||
func (a *App) runMonitor(ctx context.Context, runner sniper.Runner, accounts []sniper.Account, targets []sniper.Target, cfg sniper.Config, emit func(sniper.Result)) {
|
||||
if err := runner.RunTargets(ctx, accounts, targets, cfg, emit); err != nil && !errors.Is(err, context.Canceled) {
|
||||
a.addLog("error", "监控结束异常: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// waitFor 等到指定时刻,被取消时记录日志并返回错误。
|
||||
func (a *App) waitFor(ctx context.Context, when time.Time, label string) error {
|
||||
if !when.After(time.Now()) {
|
||||
return nil
|
||||
}
|
||||
if err := waitUntil(ctx, when); err != nil {
|
||||
a.addLog("info", "%s等待已取消", label)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// logWindowPlan 打印本次抢购的窗口区间,便于复盘「打到什么时候为止」。
|
||||
func (a *App) logWindowPlan(openAt time.Time, window time.Duration) {
|
||||
a.addLog("info", "抢购窗口: 开抢=%s 窗口=%s 结束=%s 提前=%s",
|
||||
openAt.Format("2006-01-02 15:04:05.000"), window,
|
||||
openAt.Add(window).Format("2006-01-02 15:04:05.000"), sniper.DefaultStartAhead)
|
||||
}
|
||||
|
||||
// runnerConfig 把界面配置翻译成抢购引擎配置。
|
||||
//
|
||||
// directExchange 是界面上的「直接兑换」开关:关掉时表示先查列表再兑换,
|
||||
// 也就是 ListBeforeExchange=true,这样价格/库存过滤才会生效。
|
||||
// 旧实现把 directExchange 单独透传,而引擎在 ListBeforeExchange=false 时会
|
||||
// 强制回落到直兑(见 sniper.normalizeConfig),界面开关因此形同失效。
|
||||
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,
|
||||
StopAccountAfterSuccess: cfg.StopAccountAfterSuccess,
|
||||
Prewarm: false,
|
||||
DirectExchange: cfg.DirectExchange,
|
||||
ListBeforeExchange: !cfg.DirectExchange,
|
||||
SharePrizeList: cfg.SharePrizeList,
|
||||
RefreshAfterSuccess: cfg.RefreshAfterSuccess,
|
||||
TooFrequentBackoff: time.Duration(cfg.FrequentBackoffMS) * time.Millisecond,
|
||||
ErrorBackoff: time.Duration(cfg.ErrorBackoffMS) * time.Millisecond,
|
||||
WindowSeconds: cfg.WindowSeconds,
|
||||
// 首发错峰固定用调优过的默认值:同机上百个账号齐射是最容易被限流的姿势。
|
||||
FirstWaveSpread: sniper.DefaultFirstWaveSpread,
|
||||
FirstWaveMaxStep: sniper.DefaultFirstWaveMaxStep,
|
||||
DisableAdaptiveThrottle: cfg.DisableAdaptiveThrottle,
|
||||
}
|
||||
}
|
||||
|
||||
// logRunSummary 输出任务汇总:一行总量 + 结局分布 + 接口统计 + 每账号结局。
|
||||
//
|
||||
// 复盘的痛点是「只有一堆逐条日志」:2026-10-16 的日志里既看不出限流占了多少、
|
||||
// 也不知道每个账号最后是什么下场,只能手工 grep 统计。这里一次给全。
|
||||
func (a *App) logRunSummary(summary sniper.RunSummary) {
|
||||
total := 0
|
||||
for _, count := range summary.Outcomes {
|
||||
total += count
|
||||
}
|
||||
throttled := summary.Outcomes[sniper.CategoryTooFrequent]
|
||||
window := ""
|
||||
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,
|
||||
summary.Duration.Round(time.Millisecond),
|
||||
throttled, total, percentOf(throttled, total), throttleFactorText(summary.ThrottleFactor),
|
||||
summary.ListReqs, summary.ExchangeReqs, summary.ScoreReqs, summary.RecordReqs, window)
|
||||
for _, category := range summary.Categories() {
|
||||
a.logEvent(categoryMonitor, sniper.LogLevelForCategory(category), "结局 %s ×%d(%s)",
|
||||
category, summary.Outcomes[category], sniper.CategoryLabel(category))
|
||||
}
|
||||
for _, stat := range summary.RequestStats {
|
||||
lastErr := ""
|
||||
if stat.LastErr != "" {
|
||||
lastErr = " 最后错误=" + stat.LastErr
|
||||
}
|
||||
a.logEvent(categoryMonitor, "info", "接口统计: %s ×%d 失败%d 平均=%s 最慢=%s%s",
|
||||
stat.Kind, stat.Count, stat.Failed,
|
||||
stat.Average().Round(time.Millisecond), stat.Slowest.Round(time.Millisecond), lastErr)
|
||||
}
|
||||
for _, outcome := range summary.AccountOutcomes {
|
||||
level := logger.LevelInfo
|
||||
if outcome.Category == sniper.CategorySuccess {
|
||||
level = "success"
|
||||
} else if !outcome.Done {
|
||||
level = logger.LevelWarn
|
||||
}
|
||||
a.logAccount(categoryMonitor, level, strconv.FormatInt(outcome.UID, 10),
|
||||
"最终结局=%s 尝试=%d 最后=%s", sniper.CategoryLabel(outcome.Category), outcome.Attempts, outcome.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// percentOf 计算百分比(分母为 0 时返回 0)。
|
||||
func percentOf(part, whole int) int {
|
||||
if whole <= 0 {
|
||||
return 0
|
||||
}
|
||||
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
|
||||
@@ -623,12 +774,16 @@ func normalizeConfig(cfg Config) Config {
|
||||
cfg.Transport = "wss"
|
||||
}
|
||||
// WSSHost 留空表示走 launch.queryHttpDns 自动解析,不在这里补默认值。
|
||||
if cfg.Loops <= 0 {
|
||||
cfg.Loops = 1
|
||||
// Loops 只作为可选上限:0(留空)表示「按窗口运行」,由 WindowSeconds 兜底。
|
||||
if cfg.Loops < 0 {
|
||||
cfg.Loops = 0
|
||||
}
|
||||
if cfg.DelayMS <= 0 {
|
||||
cfg.DelayMS = 150
|
||||
}
|
||||
if cfg.WindowSeconds <= 0 {
|
||||
cfg.WindowSeconds = sniper.DefaultWindowSeconds
|
||||
}
|
||||
if cfg.Concurrency <= 0 {
|
||||
cfg.Concurrency = 1
|
||||
}
|
||||
@@ -698,9 +853,12 @@ func parseAccounts(cfg Config) ([]sniper.Account, error) {
|
||||
return nil, errors.New("Cookie 不能为空")
|
||||
}
|
||||
selected := selectedLineSet(cfg.SelectedAccountLines)
|
||||
if len(selected) == 0 {
|
||||
return nil, errors.New("未选择账号")
|
||||
}
|
||||
accounts := make([]sniper.Account, 0, len(lines))
|
||||
for _, cookie := range lines {
|
||||
if len(selected) > 0 && !selected[cookie.lineNo] {
|
||||
if !selected[cookie.lineNo] {
|
||||
continue
|
||||
}
|
||||
uid := huya.ResolveUID(cookie.text)
|
||||
@@ -793,13 +951,15 @@ func nextClockTime(now time.Time, hour, minute, second int) time.Time {
|
||||
return target
|
||||
}
|
||||
|
||||
// waitUntil 等到指定时刻。用一次性定时器精确睡眠,避免旧实现 200ms 轮询带来的
|
||||
// 0-200ms 随机延迟(抢购时这段时间正好是关键窗口)。
|
||||
func waitUntil(ctx context.Context, when time.Time) error {
|
||||
for {
|
||||
remaining := time.Until(when)
|
||||
if remaining <= 0 {
|
||||
return nil
|
||||
}
|
||||
timer := time.NewTimer(minDuration(remaining, 200*time.Millisecond))
|
||||
timer := time.NewTimer(remaining)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
@@ -809,13 +969,6 @@ func waitUntil(ctx context.Context, when time.Time) error {
|
||||
}
|
||||
}
|
||||
|
||||
func minDuration(a, b time.Duration) time.Duration {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func errorString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
|
||||
@@ -50,6 +50,30 @@ func TestSplitCookieLinesNormalizesLineBreaks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAccountsRequiresExplicitSelection(t *testing.T) {
|
||||
cfg := Config{
|
||||
CookieText: "udb_uid=1; yyuid=1\nudb_uid=2; yyuid=2",
|
||||
}
|
||||
if _, err := parseAccounts(cfg); err == nil {
|
||||
t.Fatal("空选择不应回退为全部账号")
|
||||
}
|
||||
|
||||
cfg.SelectedAccountLines = []int{2}
|
||||
accounts, err := parseAccounts(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("parseAccounts() error = %v", err)
|
||||
}
|
||||
if len(accounts) != 1 || accounts[0].UID != 2 {
|
||||
t.Fatalf("accounts=%+v, want 仅第 2 行账号", accounts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultConfigUsesDynamicLead(t *testing.T) {
|
||||
if got := (&App{}).DefaultConfig().LeadMS; got != 0 {
|
||||
t.Fatalf("LeadMS=%d, want 0(动态提前量)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseStartTimeAcceptsClockOnly(t *testing.T) {
|
||||
t.Run("future_today", func(t *testing.T) {
|
||||
now := time.Date(2026, 7, 6, 10, 20, 30, 0, time.Local)
|
||||
@@ -139,3 +163,27 @@ func TestParseTargetsWithoutFiltersKeepsZeroValues(t *testing.T) {
|
||||
t.Fatalf("unexpected filters: %+v", targets[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunnerConfigMapsDirectExchangeToExchangeMode 验证界面「直接兑换」开关能真正
|
||||
// 切换到「先查列表」模式:引擎在 ListBeforeExchange=false 时会强制回落到直兑,
|
||||
// 所以关闭直接兑换必须同时置 ListBeforeExchange,否则开关形同失效。
|
||||
func TestRunnerConfigMapsDirectExchangeToExchangeMode(t *testing.T) {
|
||||
direct := runnerConfig(Config{
|
||||
SID: 2203,
|
||||
Loops: 3,
|
||||
DelayMS: 120,
|
||||
Concurrency: 5,
|
||||
DirectExchange: true,
|
||||
})
|
||||
if !direct.DirectExchange || direct.ListBeforeExchange {
|
||||
t.Fatalf("直接兑换模式映射错误: %+v", direct)
|
||||
}
|
||||
if direct.SID != 2203 || direct.Loops != 3 || direct.Delay != 120*time.Millisecond || direct.Concurrency != 5 {
|
||||
t.Fatalf("基础字段未透传: %+v", direct)
|
||||
}
|
||||
|
||||
list := runnerConfig(Config{SID: 2203, DirectExchange: false})
|
||||
if list.DirectExchange || !list.ListBeforeExchange {
|
||||
t.Fatalf("关闭直接兑换后应改为先查列表: %+v", list)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
"huya-go/internal/logger"
|
||||
"huya-go/internal/sniper"
|
||||
)
|
||||
|
||||
const (
|
||||
CookieStatusValid = "valid"
|
||||
CookieStatusExpired = "expired"
|
||||
CookieStatusUnknown = "unknown"
|
||||
CookieStatusInvalid = "invalid"
|
||||
|
||||
// cookieCheckAttempts 对「失效」结果连续确认:线上偶发「账号未绑定!」后下一轮
|
||||
// 就恢复,直接判死会把好 CK 清掉;与抢购引擎的 sessionLostLimit 保持一致。
|
||||
cookieCheckAttempts = 3
|
||||
cookieCheckRetryDelay = 250 * time.Millisecond
|
||||
)
|
||||
|
||||
// CookieCheckResult 描述一条 CK 的服务端可用性检查结果。
|
||||
// Status 取值:valid=可用、expired=失效/不可用、unknown=请求异常待确认、invalid=格式无法解析。
|
||||
type CookieCheckResult struct {
|
||||
Line int `json:"line"`
|
||||
UID int64 `json:"uid"`
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message,omitempty"`
|
||||
StatusCode int32 `json:"statusCode,omitempty"`
|
||||
CheckedAt int64 `json:"checkedAt"`
|
||||
}
|
||||
|
||||
// CheckCookies 用 getUserScore 对每条 CK 做真实登录态校验。
|
||||
//
|
||||
// 不依赖「能解析出 yyuid」这种本地格式判断:CK 里的 uid 还在、但登录态已经过期
|
||||
// 是最常见的失败原因。getUserScore 必须携带有效身份,因此适合作为可用性探针。
|
||||
func (a *App) CheckCookies(cfg Config) ([]CookieCheckResult, error) {
|
||||
cfg = normalizeConfig(cfg)
|
||||
lines := splitCookieLines(cfg.CookieText)
|
||||
if len(lines) == 0 {
|
||||
return nil, errors.New("Cookie 不能为空")
|
||||
}
|
||||
if cfg.SID <= 0 {
|
||||
return nil, errors.New("SID 不能为空")
|
||||
}
|
||||
|
||||
client, closeClient, err := a.newClient(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer closeClient()
|
||||
|
||||
accounts := make([]sniper.Account, len(lines))
|
||||
for i, line := range lines {
|
||||
accounts[i] = sniper.Account{UID: huya.ResolveUID(line.text), Cookie: line.text}
|
||||
}
|
||||
|
||||
results := make([]CookieCheckResult, len(lines))
|
||||
a.runConcurrent(accounts, cookieCheckConcurrency(cfg.Concurrency), func(i int, account sniper.Account) {
|
||||
results[i] = checkOneCookie(client, lines[i], account, cfg.SID, cfg.TimeoutSec)
|
||||
})
|
||||
|
||||
valid, expired, unknown, invalid := 0, 0, 0, 0
|
||||
for _, item := range results {
|
||||
switch item.Status {
|
||||
case CookieStatusValid:
|
||||
valid++
|
||||
case CookieStatusExpired:
|
||||
expired++
|
||||
case CookieStatusInvalid:
|
||||
invalid++
|
||||
default:
|
||||
unknown++
|
||||
}
|
||||
if item.Status == CookieStatusExpired {
|
||||
a.logAccount(categoryApp, logger.LevelWarn, strconv.FormatInt(item.UID, 10),
|
||||
"CK 已失效: %s (status=%d)", item.Message, item.StatusCode)
|
||||
}
|
||||
}
|
||||
a.addLog("info", "CK 检查完成: 总数=%d 可用=%d 失效=%d 检查失败=%d 格式错误=%d",
|
||||
len(results), valid, expired, unknown, invalid)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func checkOneCookie(client huya.ActivityClient, line cookieLine, account sniper.Account, sid int32, timeoutSec int) CookieCheckResult {
|
||||
result := CookieCheckResult{
|
||||
Line: line.lineNo,
|
||||
UID: account.UID,
|
||||
CheckedAt: time.Now().UnixMilli(),
|
||||
}
|
||||
if account.UID <= 0 {
|
||||
result.Status = CookieStatusInvalid
|
||||
result.Message = "无法解析 yyuid/udb_uid"
|
||||
return result
|
||||
}
|
||||
|
||||
for attempt := 0; attempt < cookieCheckAttempts; attempt++ {
|
||||
ctx, cancel := requestContext(timeoutSec)
|
||||
resp, err := client.QueryUserScore(ctx, account.UID, account.Cookie, sid)
|
||||
cancel()
|
||||
|
||||
status, message, statusCode := cookieCheckVerdict(resp, err)
|
||||
result.Status = status
|
||||
result.Message = message
|
||||
result.StatusCode = statusCode
|
||||
result.CheckedAt = time.Now().UnixMilli()
|
||||
if status != CookieStatusExpired || attempt == cookieCheckAttempts-1 {
|
||||
return result
|
||||
}
|
||||
time.Sleep(cookieCheckRetryDelay)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// cookieCheckVerdict 只把明确的登录态文案判为失效;限流、网络错误等归为 unknown,
|
||||
// 避免在服务端繁忙时把一批正常 CK 误标成失效。
|
||||
func cookieCheckVerdict(resp *huya.GetUserScoreResp, err error) (status, message string, statusCode int32) {
|
||||
if err != nil {
|
||||
message = strings.TrimSpace(err.Error())
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
message = "检查超时"
|
||||
}
|
||||
if message == "" {
|
||||
message = "请求失败"
|
||||
}
|
||||
return CookieStatusUnknown, message, 0
|
||||
}
|
||||
if resp == nil {
|
||||
return CookieStatusUnknown, "服务端未返回数据", 0
|
||||
}
|
||||
|
||||
msg := strings.TrimSpace(resp.Msg)
|
||||
if isCookieExpiredMessage(msg) {
|
||||
if msg == "" {
|
||||
msg = "登录态已失效"
|
||||
}
|
||||
return CookieStatusExpired, msg, resp.Status
|
||||
}
|
||||
if resp.Status == 200 {
|
||||
return CookieStatusValid, "CK 可用", resp.Status
|
||||
}
|
||||
if msg == "" {
|
||||
msg = fmt.Sprintf("服务端返回 status=%d", resp.Status)
|
||||
}
|
||||
return CookieStatusUnknown, msg, resp.Status
|
||||
}
|
||||
|
||||
func isCookieExpiredMessage(text string) bool {
|
||||
text = strings.ToLower(strings.TrimSpace(text))
|
||||
if text == "" {
|
||||
return false
|
||||
}
|
||||
for _, needle := range []string{
|
||||
"账号未绑定", "未绑定账号", "未绑定手机", "登录态", "登录失效", "登录过期",
|
||||
"请先登录", "请登录", "未登录", "重新登录", "会话失效", "会话过期",
|
||||
"凭证失效", "授权失效", "身份失效", "鉴权失败", "认证失败",
|
||||
"token 失效", "token失效", "cookie 失效", "cookie失效",
|
||||
"invalid token", "token expired", "unauthorized", "not logged in", "login expired",
|
||||
} {
|
||||
if strings.Contains(text, needle) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// cookieCheckConcurrency 给检查单独限流:检查不是抢购,没必要跟着 100 线程配置齐射。
|
||||
func cookieCheckConcurrency(configured int) int {
|
||||
if configured <= 0 {
|
||||
configured = 5
|
||||
}
|
||||
if configured < 3 {
|
||||
configured = 3
|
||||
}
|
||||
if configured > 10 {
|
||||
configured = 10
|
||||
}
|
||||
return configured
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
)
|
||||
|
||||
func TestCookieCheckVerdict(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
resp *huya.GetUserScoreResp
|
||||
err error
|
||||
wantStatus string
|
||||
}{
|
||||
{
|
||||
name: "valid",
|
||||
resp: &huya.GetUserScoreResp{Status: 200, Msg: "请求成功"},
|
||||
wantStatus: CookieStatusValid,
|
||||
},
|
||||
{
|
||||
name: "account_not_bound",
|
||||
resp: &huya.GetUserScoreResp{Status: 500, Msg: "账号未绑定!"},
|
||||
wantStatus: CookieStatusExpired,
|
||||
},
|
||||
{
|
||||
name: "login_expired",
|
||||
resp: &huya.GetUserScoreResp{Status: 500, Msg: "登录态已失效,请重新登录"},
|
||||
wantStatus: CookieStatusExpired,
|
||||
},
|
||||
{
|
||||
name: "too_frequent_is_unknown",
|
||||
resp: &huya.GetUserScoreResp{Status: 500, Msg: "活动太火爆了,请稍后重试"},
|
||||
wantStatus: CookieStatusUnknown,
|
||||
},
|
||||
{
|
||||
name: "timeout_is_unknown",
|
||||
err: context.DeadlineExceeded,
|
||||
wantStatus: CookieStatusUnknown,
|
||||
},
|
||||
{
|
||||
name: "nil_response_is_unknown",
|
||||
wantStatus: CookieStatusUnknown,
|
||||
},
|
||||
{
|
||||
name: "network_error_is_unknown",
|
||||
err: errors.New("connection reset"),
|
||||
wantStatus: CookieStatusUnknown,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, _, _ := cookieCheckVerdict(tt.resp, tt.err)
|
||||
if got != tt.wantStatus {
|
||||
t.Fatalf("cookieCheckVerdict() status = %q, want %q", got, tt.wantStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieCheckConcurrency(t *testing.T) {
|
||||
tests := []struct {
|
||||
input int
|
||||
want int
|
||||
}{
|
||||
{input: 0, want: 5},
|
||||
{input: 1, want: 3},
|
||||
{input: 7, want: 7},
|
||||
{input: 50, want: 10},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := cookieCheckConcurrency(tt.input); got != tt.want {
|
||||
t.Fatalf("cookieCheckConcurrency(%d) = %d, want %d", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"huya-go/internal/wup"
|
||||
)
|
||||
|
||||
// ErrProtocolResponse 表示服务端响应的结构与协议约定不符(典型是缺少 tRsp/tResp)。
|
||||
//
|
||||
// 这类错误既不是网络错误也不是业务失败:它说明服务端回了一个解不出来的包
|
||||
// (风控拦截、错误信封、被截断的帧都可能)。单独标记出来是为了让上层能把它
|
||||
// 与普通失败分开统计(见 sniper.CategoryProtocol),并在报错里带上 WUP 诊断信息。
|
||||
var ErrProtocolResponse = errors.New("协议响应异常")
|
||||
|
||||
// rawFrameHeadBytes 是 debug 日志里打印的原始帧前缀长度。
|
||||
const rawFrameHeadBytes = 32
|
||||
|
||||
// protocolResponseError 组装「缺少 tRsp/tResp」错误,并带上 WUP 响应诊断。
|
||||
//
|
||||
// 过去这里只有一句文案,服务端返回的 iRet/status/context 全被丢掉,
|
||||
// 事后只能重放抓包(2026-10-16 pc-3 同一账号连续 13 次命中,无法定性)。
|
||||
func protocolResponseError(service, method string, resp *wup.Response) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("%w: %s.%s 响应缺少 tRsp/tResp", ErrProtocolResponse, service, method)
|
||||
}
|
||||
return fmt.Errorf("%w: %s.%s 响应缺少 tRsp/tResp(%s)", ErrProtocolResponse, service, method, resp.Diagnose())
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"huya-go/internal/wup"
|
||||
)
|
||||
|
||||
// TestProtocolResponseErrorCarriesDiagnostics 验证「缺少 tRsp/tResp」错误会带上 WUP 诊断信息,
|
||||
// 并且可以用 errors.Is 判定——上层据此把它单独归类(sniper.CategoryProtocol),
|
||||
// 而不是混进普通失败里(2026-10-16 pc-3 同一账号连续 13 次命中该错误)。
|
||||
func TestProtocolResponseErrorCarriesDiagnostics(t *testing.T) {
|
||||
resp := &wup.Response{
|
||||
Message: -1,
|
||||
Status: map[string]string{"STATUS_RESULT_CODE": "-1"},
|
||||
NewData: map[string][]byte{"tErr": {0x0c}},
|
||||
}
|
||||
err := protocolResponseError(ServantWebActUI, FuncExchangePrize, resp)
|
||||
if !errors.Is(err, ErrProtocolResponse) {
|
||||
t.Fatalf("错误应可用 errors.Is(ErrProtocolResponse) 判定: %v", err)
|
||||
}
|
||||
text := err.Error()
|
||||
for _, want := range []string{
|
||||
"响应缺少 tRsp/tResp",
|
||||
"iRet=-1",
|
||||
"STATUS_RESULT_CODE=-1",
|
||||
"keys={tErr(1B)}",
|
||||
} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("错误信息 %q 缺少 %q", text, want)
|
||||
}
|
||||
}
|
||||
|
||||
empty := protocolResponseError(ServantWebActUI, FuncExchangePrize, nil)
|
||||
if !errors.Is(empty, ErrProtocolResponse) || !strings.Contains(empty.Error(), "响应缺少 tRsp/tResp") {
|
||||
t.Fatalf("空响应错误=%v", empty)
|
||||
}
|
||||
if errors.Is(errors.New("timeout"), ErrProtocolResponse) {
|
||||
t.Fatal("普通错误不该被判定为协议错误")
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ type HTTPClient struct {
|
||||
Endpoint string
|
||||
Client *http.Client
|
||||
Logger func(string)
|
||||
// timeHistory 保存最近几次校准偏移,用于中位数平滑。
|
||||
timeHistory OffsetHistory
|
||||
}
|
||||
|
||||
type CallOptions struct {
|
||||
@@ -29,16 +31,38 @@ type CallOptions struct {
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// DefaultMaxConnsPerHost 是多账号抢购时允许的每主机连接数。
|
||||
// Go 默认 Transport 的 MaxIdleConnsPerHost 只有 2,多账号并发时连接会被反复
|
||||
// 建立/丢弃(参考 dygou_go 的 http.Transport 调参),这里放宽到能覆盖常见并发档位。
|
||||
const (
|
||||
DefaultMaxConnsPerHost = 64
|
||||
DefaultMaxIdleConns = 128
|
||||
DefaultMaxIdleConnsPerHost = 64
|
||||
)
|
||||
|
||||
func NewHTTPClient(logger func(string)) *HTTPClient {
|
||||
return &HTTPClient{
|
||||
Endpoint: DefaultCDNWSEndpoint,
|
||||
Client: &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
Timeout: 15 * time.Second,
|
||||
Transport: newDefaultTransport(),
|
||||
},
|
||||
Logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// newDefaultTransport 构造带连接池参数的 Transport,避免多账号并发时退化成
|
||||
// 每次请求都新建连接。
|
||||
func newDefaultTransport() *http.Transport {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.MaxConnsPerHost = DefaultMaxConnsPerHost
|
||||
transport.MaxIdleConns = DefaultMaxIdleConns
|
||||
transport.MaxIdleConnsPerHost = DefaultMaxIdleConnsPerHost
|
||||
transport.IdleConnTimeout = 30 * time.Second
|
||||
transport.ForceAttemptHTTP2 = true
|
||||
return transport
|
||||
}
|
||||
|
||||
func (c *HTTPClient) logf(format string, args ...any) {
|
||||
if c.Logger != nil {
|
||||
c.Logger(fmt.Sprintf(format, args...))
|
||||
@@ -88,6 +112,31 @@ func (c *HTTPClient) PingSignal(ctx context.Context, uid int64, cookie string) (
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// PingSignalSample 调一次 launch.pingSignal 并返回可用于时间校准的样本。
|
||||
func (c *HTTPClient) PingSignalSample(ctx context.Context, uid int64, cookie string) (TimeSample, error) {
|
||||
return pingSignalSampleWith(func(req *PingSignalReq, resp *PingSignalResp) error {
|
||||
_, err := c.CallRPC(ctx, ServantLaunch, FuncPingSignal, req, resp, CallOptions{
|
||||
UID: uid,
|
||||
GUID: CookieValue(cookie, "guid"),
|
||||
Cookie: cookie,
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// CalibrateServerTime 用 pingSignal 的服务端时间戳做多轮校准(实现 TimeCalibrator)。
|
||||
func (c *HTTPClient) CalibrateServerTime(ctx context.Context, uid int64, cookie string, rounds int) (TimeCalibration, error) {
|
||||
calibration, err := RunTimeCalibration(ctx, rounds, &c.timeHistory, func(ctx context.Context) (TimeSample, error) {
|
||||
return c.PingSignalSample(ctx, uid, cookie)
|
||||
})
|
||||
if err != nil {
|
||||
c.logf("[HTTP] 时间校准失败: %v", err)
|
||||
return calibration, err
|
||||
}
|
||||
c.logf("[HTTP] 时间校准完成: %s", calibration.Summary())
|
||||
return calibration, nil
|
||||
}
|
||||
|
||||
func (c *HTTPClient) CallRPC(ctx context.Context, service, method string, reqStruct taf.Marshaler, respStruct taf.Unmarshaler, opt CallOptions) (*wup.Response, error) {
|
||||
if opt.RequestID == 0 {
|
||||
opt.RequestID = 1
|
||||
@@ -155,6 +204,9 @@ func (c *HTTPClient) CallRPC(ctx context.Context, service, method string, reqStr
|
||||
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("http status %d: %s", httpResp.StatusCode, string(respBody[:min(len(respBody), 200)]))
|
||||
}
|
||||
// debug 级打印原始帧前缀:协议异常(缺少 tRsp)时这是唯一的现场证据。
|
||||
c.logf("[HTTP] 响应 %s.%s status=%d %dB head=%s",
|
||||
service, method, httpResp.StatusCode, len(respBody), wup.HexHead(respBody, rawFrameHeadBytes))
|
||||
|
||||
var resp wup.Response
|
||||
if err := resp.Decode(respBody); err != nil {
|
||||
@@ -166,7 +218,7 @@ func (c *HTTPClient) CallRPC(ctx context.Context, service, method string, reqStr
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s.%s 响应缺少 tRsp/tResp", service, method)
|
||||
return nil, protocolResponseError(service, method, &resp)
|
||||
}
|
||||
}
|
||||
return &resp, nil
|
||||
|
||||
@@ -217,8 +217,8 @@ func (r *PingSignalResp) ReadFrom(rd *taf.Reader) error {
|
||||
|
||||
// ServerElapsed 返回服务端 signal_ap_start/end 的差值(毫秒),不可得时返回 0。
|
||||
func (r PingSignalResp) ServerElapsed() time.Duration {
|
||||
start, okStart := r.Values["signal_ap_start"]
|
||||
end, okEnd := r.Values["signal_ap_end"]
|
||||
start, okStart := r.Values[PingSignalStartKey]
|
||||
end, okEnd := r.Values[PingSignalEndKey]
|
||||
if !okStart || !okEnd || end < start {
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultTimeCalibrationRounds 是默认采样轮数:3 轮 pingSignal 只有几百毫秒,
|
||||
// 抢购准备阶段完全承受得起,换来的是「取最优样本 + 中位数平滑」。
|
||||
DefaultTimeCalibrationRounds = 3
|
||||
// timeCalibrationGap 是两轮采样之间的间隔,避免几次请求压在同一个毫秒里。
|
||||
timeCalibrationGap = 120 * time.Millisecond
|
||||
// timeCalibrationHistorySize 是参与中位数平滑的历史偏移个数。
|
||||
timeCalibrationHistorySize = 3
|
||||
|
||||
minPlausibleServerYear = 2020
|
||||
maxPlausibleServerYear = 2100
|
||||
|
||||
// PingSignalStartKey / PingSignalEndKey 是 launch.pingSignal 响应里的服务端时间戳字段。
|
||||
PingSignalStartKey = "signal_ap_start"
|
||||
PingSignalEndKey = "signal_ap_end"
|
||||
)
|
||||
|
||||
// TimeSample 是一次服务端时间采样的原始观测。
|
||||
type TimeSample struct {
|
||||
ServerAt time.Time // 服务端墙钟时间(pingSignal 的 signal_ap_start)
|
||||
SentAt time.Time // 本机发出请求的时刻
|
||||
RecvAt time.Time // 本机收到响应的时刻
|
||||
}
|
||||
|
||||
// RTT 返回这次采样的往返耗时。
|
||||
func (s TimeSample) RTT() time.Duration { return s.RecvAt.Sub(s.SentAt) }
|
||||
|
||||
// ErrorBound 返回这次采样的误差上界。
|
||||
//
|
||||
// 服务端时间戳说明的是「请求到达服务端时」,具体落在 [SentAt, RecvAt] 的哪一点
|
||||
// 无法得知,按最坏情况取半个 RTT。
|
||||
func (s TimeSample) ErrorBound() time.Duration { return s.RTT() / 2 }
|
||||
|
||||
// Offset 返回「服务端时间 - 本机时间」的估计值。
|
||||
//
|
||||
// 服务端在收到请求时打时间戳,而本机对应的时刻约为 SentAt + RTT/2(单程延迟),
|
||||
// 两者相减即为钟差。
|
||||
func (s TimeSample) Offset() time.Duration {
|
||||
mid := s.SentAt.Add(s.RTT() / 2)
|
||||
return s.ServerAt.Sub(mid)
|
||||
}
|
||||
|
||||
// TimeCalibration 是一次服务端时间校准的结果。
|
||||
type TimeCalibration struct {
|
||||
// Offset 是「服务端时间 - 本机时间」的估计偏差。
|
||||
Offset time.Duration
|
||||
// ErrorBound 是最优样本的误差上界(RTT/2)。
|
||||
ErrorBound time.Duration
|
||||
// RTT 是最优样本的往返耗时。
|
||||
RTT time.Duration
|
||||
// Samples 是实际成功的采样轮数。
|
||||
Samples int
|
||||
// At 是校准完成的本机时刻。
|
||||
At time.Time
|
||||
// Smoothed 表示 Offset 经过中位数平滑(多轮样本来回抖动时更稳)。
|
||||
Smoothed bool
|
||||
}
|
||||
|
||||
// ServerNow 返回按偏移换算的服务端当前时间(UTC)。
|
||||
func (c TimeCalibration) ServerNow() time.Time {
|
||||
if c.At.IsZero() {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
return time.Now().Add(c.Offset).UTC()
|
||||
}
|
||||
|
||||
// Summary 输出一行可读摘要,供 CLI 与 GUI 日志复用。
|
||||
func (c TimeCalibration) Summary() string {
|
||||
smoothed := ""
|
||||
if c.Smoothed {
|
||||
smoothed = " 已平滑"
|
||||
}
|
||||
return fmt.Sprintf("服务端=%s 本机偏移=%+dms 误差<=%dms RTT=%dms 样本=%d%s",
|
||||
c.ServerNow().Format("2006-01-02 15:04:05.000"),
|
||||
c.Offset.Milliseconds(),
|
||||
c.ErrorBound.Milliseconds(),
|
||||
c.RTT.Milliseconds(),
|
||||
c.Samples,
|
||||
smoothed,
|
||||
)
|
||||
}
|
||||
|
||||
// AlignedTriggerTime 把「按服务端时间理解的目标时刻」换算成本机应当触发的时刻。
|
||||
//
|
||||
// offset 是「服务端 - 本机」的偏差:本机比服务端慢时为正,触发时刻要相应提前。
|
||||
// offset 为 0 时退化为原来的 target - lead。
|
||||
func AlignedTriggerTime(target time.Time, lead, offset time.Duration) time.Time {
|
||||
return target.Add(-lead - offset)
|
||||
}
|
||||
|
||||
// TimeSampler 采一次服务端时间样本。
|
||||
type TimeSampler func(ctx context.Context) (TimeSample, error)
|
||||
|
||||
// OffsetHistory 保存最近几次偏移用于中位数平滑。
|
||||
//
|
||||
// 单次采样会被一次网络抖动带偏,取中位数能滤掉跳变(对齐 dygou_go 的 smoothedOffset)。
|
||||
type OffsetHistory struct {
|
||||
mu sync.Mutex
|
||||
values []time.Duration
|
||||
}
|
||||
|
||||
// Add 记录一次偏移,只保留最近 timeCalibrationHistorySize 个。
|
||||
func (h *OffsetHistory) Add(offset time.Duration) {
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.values = append(h.values, offset)
|
||||
if len(h.values) > timeCalibrationHistorySize {
|
||||
h.values = h.values[len(h.values)-timeCalibrationHistorySize:]
|
||||
}
|
||||
}
|
||||
|
||||
// Median 返回历史偏移的中位数与样本个数;没有历史时返回 (0, 0)。
|
||||
func (h *OffsetHistory) Median() (time.Duration, int) {
|
||||
if h == nil {
|
||||
return 0, 0
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.values) == 0 {
|
||||
return 0, 0
|
||||
}
|
||||
sorted := append([]time.Duration(nil), h.values...)
|
||||
sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
|
||||
return sorted[len(sorted)/2], len(sorted)
|
||||
}
|
||||
|
||||
// RunTimeCalibration 执行多轮采样并给出校准结果。
|
||||
//
|
||||
// 取「误差上界最小、其次 RTT 最低」的那次作为本轮结果,再对最近几次偏移取中位数
|
||||
// 做平滑;一次成功样本都没有时返回错误,由调用方回退到本机时钟。
|
||||
func RunTimeCalibration(ctx context.Context, rounds int, history *OffsetHistory, sampler TimeSampler) (TimeCalibration, error) {
|
||||
if rounds <= 0 {
|
||||
rounds = DefaultTimeCalibrationRounds
|
||||
}
|
||||
var (
|
||||
best TimeSample
|
||||
samples int
|
||||
lastErr error
|
||||
)
|
||||
for i := 0; i < rounds; i++ {
|
||||
if i > 0 {
|
||||
if err := sleepOrDone(ctx, timeCalibrationGap); err != nil {
|
||||
lastErr = err
|
||||
break
|
||||
}
|
||||
}
|
||||
sample, err := sampler(ctx)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
samples++
|
||||
if best.ServerAt.IsZero() || betterTimeSample(sample, best) {
|
||||
best = sample
|
||||
}
|
||||
}
|
||||
if best.ServerAt.IsZero() {
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("没有可用的服务端时间样本")
|
||||
}
|
||||
return TimeCalibration{}, lastErr
|
||||
}
|
||||
|
||||
calibration := TimeCalibration{
|
||||
Offset: best.Offset(),
|
||||
ErrorBound: best.ErrorBound(),
|
||||
RTT: best.RTT(),
|
||||
Samples: samples,
|
||||
At: time.Now(),
|
||||
}
|
||||
history.Add(calibration.Offset)
|
||||
if smoothed, count := history.Median(); count >= 2 {
|
||||
calibration.Offset = smoothed
|
||||
calibration.Smoothed = true
|
||||
}
|
||||
return calibration, nil
|
||||
}
|
||||
|
||||
// betterTimeSample 按「误差上界小者优先,其次 RTT 小者」挑选样本。
|
||||
func betterTimeSample(candidate, current TimeSample) bool {
|
||||
if candidate.ErrorBound() != current.ErrorBound() {
|
||||
return candidate.ErrorBound() < current.ErrorBound()
|
||||
}
|
||||
return candidate.RTT() < current.RTT()
|
||||
}
|
||||
|
||||
// TimeCalibrator 抽象服务端时间校准能力:HTTP 与 WSS 传输都实现它。
|
||||
type TimeCalibrator interface {
|
||||
CalibrateServerTime(ctx context.Context, uid int64, cookie string, rounds int) (TimeCalibration, error)
|
||||
}
|
||||
|
||||
// TryCalibrateServerTime 对活动客户端做一次服务端时间校准。
|
||||
// 传输层不支持时返回错误,调用方应回退到本机时钟。
|
||||
func TryCalibrateServerTime(ctx context.Context, client ActivityClient, uid int64, cookie string, rounds int) (TimeCalibration, error) {
|
||||
calibrator, ok := client.(TimeCalibrator)
|
||||
if !ok {
|
||||
return TimeCalibration{}, errors.New("当前传输层不支持服务端时间校准")
|
||||
}
|
||||
return calibrator.CalibrateServerTime(ctx, uid, cookie, rounds)
|
||||
}
|
||||
|
||||
// ServerTimestamp 返回 pingSignal 响应里的服务端墙钟时间。
|
||||
//
|
||||
// 2026-10-13 抓包确认(夹具见 launch_test.go 的 realPingSignalRspHex):
|
||||
// signal_ap_start / signal_ap_end 是 Unix 毫秒时间戳,两者相差 13ms——start 是
|
||||
// 服务端收到请求的时刻,end 是写出响应的时刻,校准用 start 更贴近单程中点。
|
||||
func (r PingSignalResp) ServerTimestamp() (time.Time, bool) {
|
||||
for _, key := range []string{PingSignalStartKey, PingSignalEndKey} {
|
||||
ms, ok := r.Values[key]
|
||||
if !ok || ms <= 0 {
|
||||
continue
|
||||
}
|
||||
at := time.UnixMilli(ms).UTC()
|
||||
if year := at.Year(); year < minPlausibleServerYear || year > maxPlausibleServerYear {
|
||||
// 单位或字段语义变了,宁可不用也不要按错误的偏移去对齐触发时刻。
|
||||
continue
|
||||
}
|
||||
return at, true
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// pingSignalSampleWith 在给定的 pingSignal 调用上采集一次时间样本。
|
||||
// HTTP 与 WSS 两条链路只有底层调用方式不同,采样与解析逻辑共用这一份。
|
||||
func pingSignalSampleWith(call func(req *PingSignalReq, resp *PingSignalResp) error) (TimeSample, error) {
|
||||
req := &PingSignalReq{Extra: map[string]string{}}
|
||||
var resp PingSignalResp
|
||||
sentAt := time.Now()
|
||||
if err := call(req, &resp); err != nil {
|
||||
return TimeSample{}, err
|
||||
}
|
||||
recvAt := time.Now()
|
||||
|
||||
serverAt, ok := resp.ServerTimestamp()
|
||||
if !ok {
|
||||
return TimeSample{}, fmt.Errorf("pingSignal 响应缺少可用的服务端时间戳: %v", resp.Values)
|
||||
}
|
||||
return TimeSample{ServerAt: serverAt, SentAt: sentAt, RecvAt: recvAt}, nil
|
||||
}
|
||||
|
||||
func sleepOrDone(ctx context.Context, d time.Duration) error {
|
||||
if d <= 0 {
|
||||
return ctx.Err()
|
||||
}
|
||||
timer := time.NewTimer(d)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package huya
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestServerTimestampFromRealPingSignalPayload 用 2026-10-13 的真实报文夹具验证:
|
||||
// signal_ap_* 是 Unix 毫秒时间戳,能被解析成正确的墙钟时间。
|
||||
func TestServerTimestampFromRealPingSignalPayload(t *testing.T) {
|
||||
var resp PingSignalResp
|
||||
readStructPayload(t, mustDecodeHex(t, realPingSignalRspHex), &resp)
|
||||
|
||||
at, ok := resp.ServerTimestamp()
|
||||
if !ok {
|
||||
t.Fatalf("ServerTimestamp() 未识别真实报文里的时间戳: %v", resp.Values)
|
||||
}
|
||||
want := time.UnixMilli(1791891743288).UTC()
|
||||
if !at.Equal(want) {
|
||||
t.Fatalf("ServerTimestamp()=%s, want %s", at, want)
|
||||
}
|
||||
// 夹具来自 2026-10-13 的抓包,时间戳必须落在那天(北京时间为 19:42)。
|
||||
if year, month, day := at.In(time.FixedZone("CST", 8*3600)).Date(); year != 2026 || month != time.October || day != 13 {
|
||||
t.Fatalf("服务端时间日期=%d-%02d-%02d, want 2026-10-13", year, month, day)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerTimestampRejectsImplausibleValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
values map[string]int64
|
||||
wantOK bool
|
||||
}{
|
||||
{name: "empty", values: map[string]int64{}, wantOK: false},
|
||||
{name: "nil", values: nil, wantOK: false},
|
||||
// 5 位数字明显不是 Unix 毫秒(会被解析成 1970 年),必须拒绝,
|
||||
// 否则会按错误偏移把触发时刻整体挪走。
|
||||
{name: "tiny value", values: map[string]int64{PingSignalStartKey: 12345}, wantOK: false},
|
||||
{name: "seconds instead of ms", values: map[string]int64{PingSignalStartKey: 1791891743}, wantOK: false},
|
||||
{name: "start wins", values: map[string]int64{
|
||||
PingSignalStartKey: 1791891743288,
|
||||
PingSignalEndKey: 1791891743301,
|
||||
}, wantOK: true},
|
||||
{name: "end fallback", values: map[string]int64{PingSignalEndKey: 1791891743288}, wantOK: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resp := PingSignalResp{Values: tt.values}
|
||||
at, ok := resp.ServerTimestamp()
|
||||
if ok != tt.wantOK {
|
||||
t.Fatalf("ServerTimestamp() ok=%v, want %v (values=%v)", ok, tt.wantOK, tt.values)
|
||||
}
|
||||
if ok && at.Equal(time.Time{}) {
|
||||
t.Fatalf("ok=true 但时间为零值")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeSampleOffsetUsesHalfRTT(t *testing.T) {
|
||||
base := time.Date(2026, 10, 16, 19, 0, 0, 0, time.UTC)
|
||||
// 本机比服务端慢 300ms:服务端在「本机发送后 40ms」打的时间戳 = base+300ms+40ms。
|
||||
sample := TimeSample{
|
||||
ServerAt: base.Add(300*time.Millisecond + 40*time.Millisecond),
|
||||
SentAt: base,
|
||||
RecvAt: base.Add(80 * time.Millisecond),
|
||||
}
|
||||
if got := sample.RTT(); got != 80*time.Millisecond {
|
||||
t.Fatalf("RTT()=%s, want 80ms", got)
|
||||
}
|
||||
if got := sample.ErrorBound(); got != 40*time.Millisecond {
|
||||
t.Fatalf("ErrorBound()=%s, want 40ms", got)
|
||||
}
|
||||
if got := sample.Offset(); got != 300*time.Millisecond {
|
||||
t.Fatalf("Offset()=%s, want 300ms", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTimeCalibrationPicksLowestErrorSample(t *testing.T) {
|
||||
base := time.Date(2026, 10, 16, 19, 0, 0, 0, time.UTC)
|
||||
rtts := []time.Duration{200 * time.Millisecond, 40 * time.Millisecond, 120 * time.Millisecond}
|
||||
index := 0
|
||||
sampler := func(ctx context.Context) (TimeSample, error) {
|
||||
rtt := rtts[index]
|
||||
index++
|
||||
return TimeSample{
|
||||
ServerAt: base.Add(500*time.Millisecond + rtt/2),
|
||||
SentAt: base,
|
||||
RecvAt: base.Add(rtt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
var history OffsetHistory
|
||||
calibration, err := RunTimeCalibration(context.Background(), 3, &history, sampler)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calibration.Samples != 3 {
|
||||
t.Fatalf("Samples=%d, want 3", calibration.Samples)
|
||||
}
|
||||
if calibration.RTT != 40*time.Millisecond || calibration.ErrorBound != 20*time.Millisecond {
|
||||
t.Fatalf("应取误差最小的样本: RTT=%s ErrorBound=%s", calibration.RTT, calibration.ErrorBound)
|
||||
}
|
||||
if calibration.Offset != 500*time.Millisecond {
|
||||
t.Fatalf("Offset=%s, want 500ms", calibration.Offset)
|
||||
}
|
||||
if calibration.Smoothed {
|
||||
t.Fatalf("首轮只有一个样本时不应标记为已平滑")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTimeCalibrationSmoothsOutlierWithMedian 验证中位数平滑能过滤单轮跳变。
|
||||
func TestRunTimeCalibrationSmoothsOutlierWithMedian(t *testing.T) {
|
||||
base := time.Date(2026, 10, 16, 19, 0, 0, 0, time.UTC)
|
||||
offsets := []time.Duration{100 * time.Millisecond, 900 * time.Millisecond, 100 * time.Millisecond}
|
||||
var history OffsetHistory
|
||||
var calibration TimeCalibration
|
||||
for _, offset := range offsets {
|
||||
offset := offset
|
||||
sampler := func(ctx context.Context) (TimeSample, error) {
|
||||
return TimeSample{
|
||||
ServerAt: base.Add(offset),
|
||||
SentAt: base,
|
||||
RecvAt: base, // RTT=0,Offset 就等于偏移本身
|
||||
}, nil
|
||||
}
|
||||
var err error
|
||||
calibration, err = RunTimeCalibration(context.Background(), 1, &history, sampler)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !calibration.Smoothed {
|
||||
t.Fatalf("多轮采样后应标记为已平滑")
|
||||
}
|
||||
if calibration.Offset != 100*time.Millisecond {
|
||||
t.Fatalf("Offset=%s, want 100ms(900ms 的跳变应被中位数滤掉)", calibration.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTimeCalibrationFallsBackWhenAllSamplesFail(t *testing.T) {
|
||||
failure := errors.New("pingSignal 不可用")
|
||||
sampler := func(ctx context.Context) (TimeSample, error) { return TimeSample{}, failure }
|
||||
|
||||
var history OffsetHistory
|
||||
calibration, err := RunTimeCalibration(context.Background(), 2, &history, sampler)
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("err=%v, want %v", err, failure)
|
||||
}
|
||||
if !calibration.At.IsZero() || calibration.Samples != 0 {
|
||||
t.Fatalf("失败时不应返回可用校准: %+v", calibration)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTimeCalibrationToleratesPartialFailure(t *testing.T) {
|
||||
base := time.Date(2026, 10, 16, 19, 0, 0, 0, time.UTC)
|
||||
round := 0
|
||||
sampler := func(ctx context.Context) (TimeSample, error) {
|
||||
round++
|
||||
if round != 2 {
|
||||
return TimeSample{}, errors.New("偶发失败")
|
||||
}
|
||||
return TimeSample{ServerAt: base.Add(150 * time.Millisecond), SentAt: base, RecvAt: base}, nil
|
||||
}
|
||||
|
||||
var history OffsetHistory
|
||||
calibration, err := RunTimeCalibration(context.Background(), 3, &history, sampler)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calibration.Samples != 1 {
|
||||
t.Fatalf("Samples=%d, want 1", calibration.Samples)
|
||||
}
|
||||
if calibration.Offset != 150*time.Millisecond {
|
||||
t.Fatalf("Offset=%s, want 150ms", calibration.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlignedTriggerTimeCompensatesClockSkew(t *testing.T) {
|
||||
target := time.Date(2026, 10, 16, 20, 0, 0, 0, time.Local)
|
||||
tests := []struct {
|
||||
name string
|
||||
lead time.Duration
|
||||
offset time.Duration
|
||||
want time.Time
|
||||
}{
|
||||
{name: "no skew", lead: 2500 * time.Millisecond, offset: 0, want: target.Add(-2500 * time.Millisecond)},
|
||||
// 本机比服务端慢 300ms:服务端的 20:00:00 发生在本机 19:59:59.700,再提前 lead。
|
||||
{name: "local behind", lead: 2500 * time.Millisecond, offset: 300 * time.Millisecond, want: target.Add(-2800 * time.Millisecond)},
|
||||
// 本机比服务端快 300ms:本机 20:00:00.300 才是服务端的 20:00:00。
|
||||
{name: "local ahead", lead: 2500 * time.Millisecond, offset: -300 * time.Millisecond, want: target.Add(-2200 * time.Millisecond)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := AlignedTriggerTime(target, tt.lead, tt.offset); !got.Equal(tt.want) {
|
||||
t.Fatalf("AlignedTriggerTime()=%s, want %s", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeCalibrationServerNowAppliesOffset(t *testing.T) {
|
||||
calibration := TimeCalibration{Offset: 2 * time.Second, At: time.Now()}
|
||||
before := time.Now().Add(2 * time.Second).UTC()
|
||||
got := calibration.ServerNow()
|
||||
if got.Before(before.Add(-100*time.Millisecond)) || got.After(before.Add(100*time.Millisecond)) {
|
||||
t.Fatalf("ServerNow()=%s, 偏离预期 %s 太多", got, before)
|
||||
}
|
||||
var zero TimeCalibration
|
||||
if zero.ServerNow().IsZero() {
|
||||
t.Fatalf("未校准时应退化为本机时间")
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,8 @@ type WSSClient struct {
|
||||
dnsInflight chan struct{}
|
||||
// dnsFailedAt 记录解析失败时间,冷却期内不再重复请求。
|
||||
dnsFailedAt time.Time
|
||||
// timeHistory 保存最近几次校准偏移,用于中位数平滑。
|
||||
timeHistory OffsetHistory
|
||||
}
|
||||
|
||||
type WSSSession struct {
|
||||
@@ -152,6 +154,31 @@ func (c *WSSClient) PingSignal(ctx context.Context, uid int64, cookie string) (*
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// PingSignalSample 通过 WSS 通道调一次 pingSignal 并返回可用于时间校准的样本。
|
||||
func (c *WSSClient) PingSignalSample(ctx context.Context, uid int64, cookie string) (TimeSample, error) {
|
||||
session, err := c.session(ctx, uid, cookie)
|
||||
if err != nil {
|
||||
return TimeSample{}, err
|
||||
}
|
||||
return pingSignalSampleWith(func(req *PingSignalReq, resp *PingSignalResp) error {
|
||||
_, err := session.callRPC(ctx, ServantLaunch, FuncPingSignal, req, resp)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// CalibrateServerTime 用 pingSignal 的服务端时间戳做多轮校准(实现 TimeCalibrator)。
|
||||
func (c *WSSClient) CalibrateServerTime(ctx context.Context, uid int64, cookie string, rounds int) (TimeCalibration, error) {
|
||||
calibration, err := RunTimeCalibration(ctx, rounds, &c.timeHistory, func(ctx context.Context) (TimeSample, error) {
|
||||
return c.PingSignalSample(ctx, uid, cookie)
|
||||
})
|
||||
if err != nil {
|
||||
c.logf("[WSS] 时间校准失败: %v", err)
|
||||
return calibration, err
|
||||
}
|
||||
c.logf("[WSS] 时间校准完成: %s", calibration.Summary())
|
||||
return calibration, nil
|
||||
}
|
||||
|
||||
// resolveHost 返回本次建连使用的 host。
|
||||
//
|
||||
// 优先级:显式配置的 Host > queryHttpDns 结果(TTL 内缓存、多 host 轮询)> DefaultWSSHost。
|
||||
@@ -421,9 +448,13 @@ func (s *WSSSession) readLoop() {
|
||||
case WSSCmdWupRsp:
|
||||
var resp wup.Response
|
||||
if err := resp.Decode(cmd.Data); err != nil {
|
||||
s.client.logf("[WSS] 解码 WUP 响应失败: %v", err)
|
||||
s.client.logf("[WSS] 解码 WUP 响应失败: %v (cmd=%d data=%dB head=%s)",
|
||||
err, cmd.CmdType, len(cmd.Data), wup.HexHead(cmd.Data, rawFrameHeadBytes))
|
||||
continue
|
||||
}
|
||||
// debug 级打印原始帧前缀:协议异常(缺少 tRsp)时这是唯一的现场证据。
|
||||
s.client.logf("[WSS] 收到 WUP 响应 requestID=%d data=%dB head=%s",
|
||||
resp.RequestID, len(cmd.Data), wup.HexHead(cmd.Data, rawFrameHeadBytes))
|
||||
s.resolveRequest(resp.RequestID, rpcResult{resp: &resp})
|
||||
case WSSCmdHeartBeatAck, WSSCmdHeartBeatRsp:
|
||||
// 心跳响应无需处理。
|
||||
@@ -685,7 +716,7 @@ func (s *WSSSession) callRPC(ctx context.Context, service, method string, reqStr
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s.%s 响应缺少 tRsp/tResp", service, method)
|
||||
return nil, protocolResponseError(service, method, resp)
|
||||
}
|
||||
}
|
||||
return resp, nil
|
||||
|
||||
@@ -0,0 +1,859 @@
|
||||
package sniper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
)
|
||||
|
||||
// TestClassifyExchangeThrottleTexts 覆盖 2026-10-16 三台机器日志里真实出现过的限流文案。
|
||||
//
|
||||
// 这些文案过去全部落到 failed:既看不出被限流,也享受不到限流该有的退避语义
|
||||
// (pc-1 的 1421 次请求里 917 次「活动太火爆」+ 244 次「领取频率限制」)。
|
||||
func TestClassifyExchangeThrottleTexts(t *testing.T) {
|
||||
throttleTexts := []string{
|
||||
"活动太火爆了,请稍后重试",
|
||||
"领取频率限制,请稍后重试!!",
|
||||
"请求太频繁,请稍后重试",
|
||||
"操作频繁,请稍后再试",
|
||||
"当前网络繁忙,请稍后重试",
|
||||
"您点击太快,请稍等再试",
|
||||
}
|
||||
for _, text := range throttleTexts {
|
||||
resp := &huya.ScoreExchangePrizeResp{Status: 500, Msg: text}
|
||||
if got := ClassifyExchange(resp, nil); got != CategoryTooFrequent {
|
||||
t.Fatalf("ClassifyExchange(%q)=%s, want %s", text, got, CategoryTooFrequent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassifyExchangeOrderPrefersSpecificReason 验证具体原因优先于限流:
|
||||
// 「库存不足,请稍后重试」必须判成售罄而不是限流。
|
||||
func TestClassifyExchangeOrderPrefersSpecificReason(t *testing.T) {
|
||||
cases := []struct {
|
||||
text string
|
||||
want string
|
||||
}{
|
||||
{text: "库存不足,请稍后重试", want: CategorySoldOut},
|
||||
{text: "该奖品已抢完", want: CategorySoldOut},
|
||||
{text: "兑换货币不足,请参与活动获得兑换货币", want: CategoryNotEnough},
|
||||
{text: "奖品暂未开放兑换", want: CategoryNotOpen},
|
||||
{text: "账号未绑定!", want: CategorySessionLost},
|
||||
{text: "登录态已失效,请重新登录", want: CategorySessionLost},
|
||||
{text: "奖品已下架", want: CategoryOffShelf},
|
||||
}
|
||||
for _, tt := range cases {
|
||||
resp := &huya.ScoreExchangePrizeResp{Status: 500, Msg: tt.text}
|
||||
if got := ClassifyExchange(resp, nil); got != tt.want {
|
||||
t.Fatalf("ClassifyExchange(%q)=%s, want %s", tt.text, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassifyExchangeProtocolError 验证协议层错误与普通失败分开归类。
|
||||
func TestClassifyExchangeProtocolError(t *testing.T) {
|
||||
protocolErr := fmt.Errorf("%w: webActUI.scoreExchangePrize 响应缺少 tRsp/tResp(iRet=-1 keys={tErr})", huya.ErrProtocolResponse)
|
||||
if got := ClassifyExchange(nil, protocolErr); got != CategoryProtocol {
|
||||
t.Fatalf("协议错误应归为 %s,实际 %s", CategoryProtocol, got)
|
||||
}
|
||||
if got := ClassifyExchange(nil, errors.New("timeout")); got != CategoryError {
|
||||
t.Fatalf("普通网络错误应归为 %s,实际 %s", CategoryError, got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCategoryLabelAndLogLevel 验证新增分类的标签与日志等级映射。
|
||||
func TestCategoryLabelAndLogLevel(t *testing.T) {
|
||||
if got := CategoryLabel(CategoryProtocol); got != "协议异常" {
|
||||
t.Fatalf("CategoryLabel(protocol)=%q", got)
|
||||
}
|
||||
if got := LogLevelForCategory(CategoryProtocol); got != "error" {
|
||||
t.Fatalf("协议异常应为 error 级,实际 %s", got)
|
||||
}
|
||||
if got := LogLevelForCategory(CategorySessionLost); got != "warn" {
|
||||
t.Fatalf("会话失效应为 warn 级,实际 %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryEscalationMath 验证退避阶梯的两个纯函数。
|
||||
func TestRetryEscalationMath(t *testing.T) {
|
||||
wantStreak := map[int]int{1: 1, 2: 1, 3: 2, 4: 4, 5: 4, 9: 4}
|
||||
for streak, want := range wantStreak {
|
||||
if got := streakMultiplier(streak); got != want {
|
||||
t.Fatalf("streakMultiplier(%d)=%d, want %d", streak, got, want)
|
||||
}
|
||||
}
|
||||
wantStage := map[time.Duration]int{
|
||||
500 * time.Millisecond: 1,
|
||||
3 * time.Second: 2,
|
||||
6 * time.Second: 3,
|
||||
}
|
||||
for elapsed, want := range wantStage {
|
||||
if got := stageMultiplier(elapsed, CategoryFailed); got != want {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
before := g.current()
|
||||
g.observe(CategorySuccess)
|
||||
if got := g.current(); got >= before {
|
||||
t.Fatalf("有进展后应回退,factor 从 %v 到 %v", before, got)
|
||||
}
|
||||
if got := g.current(); got < 1 {
|
||||
t.Fatalf("倍率不应小于 1,实际 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrefireProbeCountBounds 验证探活账号数不会跟着高并发设置无限放大。
|
||||
func TestPrefireProbeCountBounds(t *testing.T) {
|
||||
tests := []struct {
|
||||
configured int
|
||||
total int
|
||||
want int
|
||||
}{
|
||||
{configured: 0, total: 100, want: 1},
|
||||
{configured: 2, total: 100, want: 2},
|
||||
{configured: 8, total: 100, want: 8},
|
||||
{configured: 100, total: 100, want: 8},
|
||||
{configured: 5, total: 3, want: 3},
|
||||
{configured: 5, total: 0, want: 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := prefireProbeCount(tt.configured, tt.total); got != tt.want {
|
||||
t.Fatalf("prefireProbeCount(%d,%d)=%d, want %d", tt.configured, tt.total, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrewarmConcurrencyBounds 验证预热并发不会跟着抢购线程设置过低或过高。
|
||||
func TestPrewarmConcurrencyBounds(t *testing.T) {
|
||||
tests := []struct {
|
||||
input int
|
||||
want int
|
||||
}{
|
||||
{input: 0, want: 8},
|
||||
{input: 1, want: 8},
|
||||
{input: 5, want: 8},
|
||||
{input: 12, want: 12},
|
||||
{input: 100, want: 16},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := prewarmConcurrency(tt.input); got != tt.want {
|
||||
t.Fatalf("prewarmConcurrency(%d)=%d, want %d", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunStateFirstWaveStagger 验证首发错峰:第 0 个账号立即发,其余按步长错开,每个账号只生效一次。
|
||||
func TestRunStateFirstWaveStagger(t *testing.T) {
|
||||
accounts := []Account{{UID: 1, Cookie: "yyuid=1"}, {UID: 2, Cookie: "yyuid=2"}, {UID: 3, Cookie: "yyuid=3"}}
|
||||
state := newRunState(accounts, 1, 1, Config{
|
||||
OpenAt: time.Now(),
|
||||
FirstWaveSpread: DefaultFirstWaveSpread,
|
||||
FirstWaveMaxStep: DefaultFirstWaveMaxStep,
|
||||
})
|
||||
want := []time.Duration{0, DefaultFirstWaveMaxStep, 2 * DefaultFirstWaveMaxStep}
|
||||
for index, account := range accounts {
|
||||
if got := state.takeFirstWaveDelay(account.UID); got != want[index] {
|
||||
t.Fatalf("账号 %d 首发等待=%v, want %v", account.UID, got, want[index])
|
||||
}
|
||||
}
|
||||
if got := state.takeFirstWaveDelay(1); got != 0 {
|
||||
t.Fatalf("同一账号不应重复错峰,实际 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsWaitsForWindowWithoutPrefire 验证即使不需要预打,也不会提前进入窗口循环。
|
||||
func TestRunTargetsWaitsForWindowWithoutPrefire(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var first time.Time
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
mu.Lock()
|
||||
if first.IsZero() {
|
||||
first = time.Now()
|
||||
}
|
||||
mu.Unlock()
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
|
||||
},
|
||||
}
|
||||
openAt := time.Now().Add(300 * time.Millisecond)
|
||||
err := (&Runner{Client: client}).RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 1}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: openAt,
|
||||
windowOverride: 20 * time.Millisecond,
|
||||
Loops: 1,
|
||||
Delay: time.Millisecond,
|
||||
StartAhead: 100 * time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
got := first
|
||||
mu.Unlock()
|
||||
windowStart := openAt.Add(-100 * time.Millisecond)
|
||||
if got.Before(windowStart.Add(-10 * time.Millisecond)) {
|
||||
t.Fatalf("首次请求=%v, 早于窗口起点 %v", got, windowStart)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsStopAccountAfterSuccessStopsAllTargets 验证「账号成功停」是账号级开关:
|
||||
// 成功一个商品后,同一账号不应继续兑换剩余目标。
|
||||
func TestRunTargetsStopAccountAfterSuccessStopsAllTargets(t *testing.T) {
|
||||
client := &fakeActivityClient{}
|
||||
runner := Runner{Client: client}
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
|
||||
{PID: 1},
|
||||
{PID: 2},
|
||||
}, Config{
|
||||
SID: 2203,
|
||||
Loops: 2,
|
||||
Delay: time.Millisecond,
|
||||
StopAccountAfterSuccess: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exchangeCount, _ := client.counts(); exchangeCount != 1 {
|
||||
t.Fatalf("exchangeCount=%d, want 1(账号成功后应停止全部目标)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSessionLostStopsWholeAccount 验证会话连续失效达到阈值后停止整个账号,
|
||||
// 而不是只停当前目标。
|
||||
func TestRunTargetsSessionLostStopsWholeAccount(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "账号未绑定!"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
|
||||
{PID: 1},
|
||||
{PID: 2},
|
||||
}, Config{
|
||||
SID: 2203,
|
||||
Loops: 10,
|
||||
Delay: 5 * time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
SessionLostLimit: 3,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 第 1、2 轮各打两个目标;第 3 轮第一个目标连续第 3 次失效后整账号停止。
|
||||
if _, exchangeCount, _ := client.counts(); exchangeCount != 5 {
|
||||
t.Fatalf("exchangeCount=%d, want 5(达到阈值后应停止整个账号)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunStateElapsedUsesOpenAt 验证退避阶段从开抢时刻起算,而不是从提前启动时起算。
|
||||
func TestRunStateElapsedUsesOpenAt(t *testing.T) {
|
||||
state := &runState{
|
||||
startedAt: time.Now().Add(-10 * time.Second),
|
||||
openAt: time.Now().Add(-2 * time.Second),
|
||||
}
|
||||
if got := state.elapsed(); got < 1900*time.Millisecond || got > 3*time.Second {
|
||||
t.Fatalf("elapsed=%v, want 约 2s(按 openAt 计算)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsNotFoundBacksOff 验证未命中时不会每轮刷事件和列表请求。
|
||||
func TestRunTargetsNotFoundBacksOff(t *testing.T) {
|
||||
client := &fakeActivityClient{listResp: &huya.GetActPrizeListResp{Status: 200}}
|
||||
runner := Runner{Client: client}
|
||||
var notFound int32
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
|
||||
{Name: "不存在的奖品"},
|
||||
}, Config{
|
||||
SID: 2203,
|
||||
Loops: 6,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: 25 * time.Millisecond,
|
||||
ListBeforeExchange: true,
|
||||
}, func(result Result) {
|
||||
if result.Category == CategoryNotFound {
|
||||
atomic.AddInt32(¬Found, 1)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := atomic.LoadInt32(¬Found); got != 1 {
|
||||
t.Fatalf("not_found 事件=%d, want 1(退避期间应跳过)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsNotOpenBacksOff 验证未开放时也会退避,不会以 Delay 持续轰接口。
|
||||
func TestRunTargetsNotOpenBacksOff(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "奖品暂未开放兑换"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
|
||||
{PID: 1},
|
||||
}, Config{
|
||||
SID: 2203,
|
||||
Loops: 6,
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExchangeTargetSkipsAfterWindow 验证排队拿到并发额度时窗口已结束,
|
||||
// 不会把兑换请求补发到窗口外。
|
||||
func TestExchangeTargetSkipsAfterWindow(t *testing.T) {
|
||||
client := &fakeActivityClient{}
|
||||
account := Account{UID: 1, Cookie: "yyuid=1"}
|
||||
state := newRunState([]Account{account}, 1, 1, Config{
|
||||
OpenAt: time.Now().Add(-2 * time.Second),
|
||||
WindowSeconds: 1,
|
||||
})
|
||||
result := (&Runner{Client: client}).exchangeTarget(
|
||||
context.Background(), client, state, account, Target{PID: 1}, 0, 1, 2203, nil,
|
||||
)
|
||||
if result.Action != actionExchangeCanceled {
|
||||
t.Fatalf("action=%q, want %q", result.Action, actionExchangeCanceled)
|
||||
}
|
||||
if _, exchangeCount, _ := client.counts(); exchangeCount != 0 {
|
||||
t.Fatalf("exchangeCount=%d, want 0(窗口外不能补发)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsDirectExchangeHonorsPriceFilter 验证设置价格门槛后不能走直兑绕过过滤。
|
||||
func TestRunTargetsDirectExchangeHonorsPriceFilter(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
listResp: &huya.GetActPrizeListResp{
|
||||
Status: 200,
|
||||
Prizes: []huya.PrizeInfo{{ID: 1, Name: "涨价商品", NewScore: 100}},
|
||||
},
|
||||
}
|
||||
err := (&Runner{Client: client}).RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{
|
||||
{PID: 1, MaxPrice: 50},
|
||||
}, Config{
|
||||
SID: 2203,
|
||||
Loops: 1,
|
||||
Delay: time.Millisecond,
|
||||
DirectExchange: true,
|
||||
ListBeforeExchange: false,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listCount, exchangeCount, _ := client.counts()
|
||||
if listCount != 1 || exchangeCount != 0 {
|
||||
t.Fatalf("list=%d exchange=%d, want list=1 exchange=0(价格超限不能直兑)", listCount, exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsPrefireProbeIsBounded 验证预打探活最多只用一个并发批次,
|
||||
// 不会在账号很多时把请求拖到开抢之后。
|
||||
func TestRunTargetsPrefireProbeIsBounded(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := make([]time.Time, 0, 8)
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
mu.Lock()
|
||||
calls = append(calls, time.Now())
|
||||
mu.Unlock()
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "奖品暂未开放兑换"}, nil
|
||||
},
|
||||
}
|
||||
accounts := make([]Account, 0, 6)
|
||||
for uid := int64(1); uid <= 6; uid++ {
|
||||
accounts = append(accounts, Account{UID: uid, Cookie: "yyuid=1"})
|
||||
}
|
||||
openAt := time.Now().Add(350 * time.Millisecond)
|
||||
err := (&Runner{Client: client}).RunTargets(context.Background(), accounts, []Target{{PID: 1}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: openAt,
|
||||
windowOverride: 30 * time.Millisecond,
|
||||
Loops: 1,
|
||||
Delay: time.Millisecond,
|
||||
StartAhead: 20 * time.Millisecond,
|
||||
Concurrency: 2,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
windowStart := openAt.Add(-20 * time.Millisecond)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
prefire := 0
|
||||
for _, at := range calls {
|
||||
if at.Before(windowStart) {
|
||||
prefire++
|
||||
}
|
||||
}
|
||||
if prefire > 2 {
|
||||
t.Fatalf("预打请求=%d, want <= 2(仅一个并发批次)", prefire)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryDelayNeverExceedsCap 验证全局降速和抖动不能把单次退避放大到上限之外。
|
||||
func TestRetryDelayNeverExceedsCap(t *testing.T) {
|
||||
state := newRunState([]Account{{UID: 1}}, 1, 1, Config{})
|
||||
state.governor = newThrottleGovernor()
|
||||
state.governor.factor = governorMaxFactor
|
||||
for i := 0; i < 20; i++ {
|
||||
got := state.retryDelay(1, 0, Config{
|
||||
ErrorBackoff: 300 * time.Millisecond,
|
||||
TooFrequentBackoff: 300 * time.Millisecond,
|
||||
}, CategoryTooFrequent)
|
||||
if got > maxRetryDelay {
|
||||
t.Fatalf("retryDelay=%v, want <= %v", got, maxRetryDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsWindowModeKeepsTryingUntilDeadline 是 P1 的核心回归:
|
||||
// 账号很少时,旧实现会「20 轮 × 150ms」在开抢前把预算烧光(pc-3 instance-4 0 成功),
|
||||
// 窗口模式必须一直打到窗口结束。
|
||||
func TestRunTargetsWindowModeKeepsTryingUntilDeadline(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
started := time.Now()
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: started,
|
||||
windowOverride: 120 * time.Millisecond,
|
||||
Loops: 0, // 窗口模式:不限制轮次
|
||||
Delay: 5 * time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed < 100*time.Millisecond {
|
||||
t.Fatalf("窗口模式应跑到窗口结束,实际只跑了 %v", elapsed)
|
||||
}
|
||||
_, exchangeCount, _ := client.counts()
|
||||
if exchangeCount < 5 {
|
||||
t.Fatalf("窗口内应持续尝试,实际只有 %d 次", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsPrefireOnceBeforeOpen 验证开抢前只预打一轮,然后静默等到窗口起点。
|
||||
func TestRunTargetsPrefireOnceBeforeOpen(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var calls []time.Time
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
mu.Lock()
|
||||
calls = append(calls, time.Now())
|
||||
mu.Unlock()
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "奖品暂未开放兑换"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
// 触发时刻远早于窗口起点:应当先预打一轮,再静默等到窗口起点。
|
||||
openAt := time.Now().Add(500 * time.Millisecond)
|
||||
started := time.Now()
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: openAt,
|
||||
windowOverride: 60 * time.Millisecond,
|
||||
Loops: 0,
|
||||
Delay: 5 * time.Millisecond,
|
||||
StartAhead: 20 * time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
captured := append([]time.Time(nil), calls...)
|
||||
mu.Unlock()
|
||||
if len(captured) < 2 {
|
||||
t.Fatalf("应有预打 + 窗口内重试,实际 %d 次", len(captured))
|
||||
}
|
||||
windowStart := openAt.Add(-20 * time.Millisecond)
|
||||
if !captured[0].Before(windowStart.Add(-50 * time.Millisecond)) {
|
||||
t.Fatalf("第一次请求应明显早于窗口起点(预打),实际 %v(窗口起点 %v)", captured[0], windowStart)
|
||||
}
|
||||
for _, at := range captured[1:] {
|
||||
if at.Before(windowStart.Add(-30 * time.Millisecond)) {
|
||||
t.Fatalf("预打之后应等到窗口起点,实际在 %v(窗口起点 %v)", at, windowStart)
|
||||
}
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed < 500*time.Millisecond {
|
||||
t.Fatalf("应跑到窗口结束(%v),实际 %v", openAt.Add(60*time.Millisecond), elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSkipsPrefireNearWindowStart 验证触发时刻与窗口起点重合时不会把首发齐射打两遍。
|
||||
func TestRunTargetsSkipsPrefireNearWindowStart(t *testing.T) {
|
||||
client := &fakeActivityClient{}
|
||||
runner := Runner{Client: client}
|
||||
openAt := time.Now().Add(60 * time.Millisecond)
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: openAt,
|
||||
windowOverride: 40 * time.Millisecond,
|
||||
Loops: 1, // 只跑一轮,用于观察首发是否被重复
|
||||
StartAhead: 60 * time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exchangeCount, _ := client.counts(); exchangeCount != 1 {
|
||||
t.Fatalf("窗口起点附近不应额外预打,实际请求 %d 次", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsWindowAlreadyExpiredSkips 验证窗口已过时不再发请求。
|
||||
func TestRunTargetsWindowAlreadyExpiredSkips(t *testing.T) {
|
||||
client := &fakeActivityClient{}
|
||||
runner := Runner{Client: client}
|
||||
started := time.Now()
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
OpenAt: time.Now().Add(-2 * time.Second),
|
||||
windowOverride: time.Second,
|
||||
Loops: 0,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, exchangeCount, _ := client.counts(); exchangeCount != 0 {
|
||||
t.Fatalf("窗口已过不该发请求,实际 %d 次", exchangeCount)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > 200*time.Millisecond {
|
||||
t.Fatalf("窗口已过应立即返回,实际 %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSessionLostStopsAfterLimit 验证会话失效连续多次后停止该账号。
|
||||
func TestRunTargetsSessionLostStopsAfterLimit(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "账号未绑定!"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 10,
|
||||
Delay: 2 * time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
SessionLostLimit: 3,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, exchangeCount, _ := client.counts()
|
||||
if exchangeCount != 3 {
|
||||
t.Fatalf("连续失效达到阈值应停止该账号,实际请求 %d 次", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSummaryIncludesRequestAndAccountStats 验证接口统计与逐账号结局。
|
||||
func TestRunTargetsSummaryIncludesRequestAndAccountStats(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return nil, errors.New("网络抖动")
|
||||
},
|
||||
}
|
||||
var summary RunSummary
|
||||
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,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
StopAfterSuccess: true,
|
||||
}, func(Result) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var exchangeStat *RequestStat
|
||||
for index := range summary.RequestStats {
|
||||
if summary.RequestStats[index].Kind == reqExchange.String() {
|
||||
exchangeStat = &summary.RequestStats[index]
|
||||
}
|
||||
}
|
||||
if exchangeStat == nil {
|
||||
t.Fatalf("缺少兑换接口统计: %+v", summary.RequestStats)
|
||||
}
|
||||
if exchangeStat.Count < 1 || exchangeStat.Failed != exchangeStat.Count || exchangeStat.LastErr == "" {
|
||||
t.Fatalf("兑换接口统计不正确: %+v", *exchangeStat)
|
||||
}
|
||||
if exchangeStat.Slowest <= 0 {
|
||||
t.Fatalf("应记录最慢耗时: %+v", *exchangeStat)
|
||||
}
|
||||
if len(summary.AccountOutcomes) != 1 {
|
||||
t.Fatalf("应有 1 条账号结局,实际 %+v", summary.AccountOutcomes)
|
||||
}
|
||||
outcome := summary.AccountOutcomes[0]
|
||||
if outcome.UID != 7 || outcome.Category != CategoryError || outcome.Attempts < 1 {
|
||||
t.Fatalf("账号结局不正确: %+v", outcome)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlanTriggerDynamicAdvance 验证定时触发计划:动态提前量、预热/复校/窗口时刻。
|
||||
func TestPlanTriggerDynamicAdvance(t *testing.T) {
|
||||
target := time.Date(2026, 10, 16, 17, 0, 0, 0, time.Local)
|
||||
calibration := huya.TimeCalibration{
|
||||
Offset: 900 * time.Millisecond, // 本机比服务端慢 0.9s(pc-3 实测)
|
||||
ErrorBound: 30 * time.Millisecond,
|
||||
RTT: 60 * time.Millisecond,
|
||||
}
|
||||
plan := PlanTrigger(target, calibration, 0, 30*time.Second)
|
||||
|
||||
if want := 60 * time.Millisecond; plan.Advance != want {
|
||||
t.Fatalf("动态提前量=%v, want %v", plan.Advance, want)
|
||||
}
|
||||
wantOpen := target.Add(-900 * time.Millisecond)
|
||||
if !plan.OpenAt.Equal(wantOpen) {
|
||||
t.Fatalf("开抢时刻=%v, want %v", plan.OpenAt, wantOpen)
|
||||
}
|
||||
if !plan.TriggerAt.Equal(wantOpen.Add(-60 * time.Millisecond)) {
|
||||
t.Fatalf("触发时刻=%v", plan.TriggerAt)
|
||||
}
|
||||
if !plan.WarmupAt.Equal(wantOpen.Add(-WarmupLead)) {
|
||||
t.Fatalf("预热时刻=%v", plan.WarmupAt)
|
||||
}
|
||||
if !plan.ResyncAt.Equal(wantOpen.Add(-ResyncLead)) {
|
||||
t.Fatalf("复校时刻=%v", plan.ResyncAt)
|
||||
}
|
||||
if !plan.WindowEnd.Equal(wantOpen.Add(30 * time.Second)) {
|
||||
t.Fatalf("窗口结束=%v", plan.WindowEnd)
|
||||
}
|
||||
|
||||
if got := PlanTrigger(target, calibration, 2500*time.Millisecond, time.Second).Advance; got != 2500*time.Millisecond {
|
||||
t.Fatalf("显式提前量应覆盖动态值,实际 %v", got)
|
||||
}
|
||||
if got := PlanTrigger(target, huya.TimeCalibration{}, 0, time.Second).Advance; got != MinTriggerAdvance {
|
||||
t.Fatalf("提前量下限=%v, want %v", got, MinTriggerAdvance)
|
||||
}
|
||||
if got := WindowDuration(0); got != DefaultWindowSeconds*time.Second {
|
||||
t.Fatalf("默认窗口=%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsPerAccountLoopsAreIndependent 是「每账号独立循环」的核心回归:
|
||||
// 一个账号卡在慢请求上时,其他账号必须继续按自己的节奏推进。
|
||||
//
|
||||
// 旧实现按「一轮打完等所有人」(wg.Wait)同步,账号 1 的慢请求会把账号 2 的第二轮
|
||||
// 死死卡在起跑线上;账号少的实例尤其吃亏(pc-3 instance-4 因此 0 成功)。
|
||||
func TestRunTargetsPerAccountLoopsAreIndependent(t *testing.T) {
|
||||
blocked := make(chan struct{})
|
||||
entered := make(chan struct{})
|
||||
var enterOnce sync.Once
|
||||
var slowExchanges, fastExchanges int64
|
||||
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
if uid == 1 {
|
||||
atomic.AddInt64(&slowExchanges, 1)
|
||||
enterOnce.Do(func() { close(entered) })
|
||||
<-blocked
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
|
||||
}
|
||||
atomic.AddInt64(&fastExchanges, 1)
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
accounts := []Account{{UID: 1, Cookie: "yyuid=1"}, {UID: 2, Cookie: "yyuid=2"}}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- runner.RunTargets(context.Background(), accounts, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 30,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
Concurrency: 4,
|
||||
}, nil)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("账号 1 的慢请求未开始")
|
||||
}
|
||||
|
||||
// 账号 1 仍阻塞在第一个请求里:账号 2 应当已经独立跑完多轮。
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for atomic.LoadInt64(&fastExchanges) < 3 && time.Now().Before(deadline) {
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
got := atomic.LoadInt64(&fastExchanges)
|
||||
close(blocked)
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got < 3 {
|
||||
t.Fatalf("账号 1 阻塞期间账号 2 只完成了 %d 次兑换,独立循环应继续推进(want >= 3)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSharedListTTLSingleFlight 验证共享列表快照是「TTL + 单飞」:
|
||||
// 多个账号多轮里只查一次列表,既不被单次抖动拖垮,也不把名单打爆。
|
||||
//
|
||||
// 只做单飞(无 TTL)时每轮都会重新查询,2 账号 × 3 轮最坏要 6 次。
|
||||
func TestRunTargetsSharedListTTLSingleFlight(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
listResp: &huya.GetActPrizeListResp{
|
||||
Status: 200,
|
||||
Msg: "请求成功",
|
||||
Prizes: []huya.PrizeInfo{{ID: 12889, SID: 2203, Name: "套装-潮萌小黄鸭", NewScore: 988, LeftNum: 10}},
|
||||
},
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "活动太火爆了,请稍后重试"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
accounts := []Account{{UID: 1, Cookie: "yyuid=1"}, {UID: 2, Cookie: "yyuid=2"}}
|
||||
|
||||
err := runner.RunTargets(context.Background(), accounts, []Target{{Name: "小黄鸭"}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 3,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
TooFrequentBackoff: time.Millisecond,
|
||||
Concurrency: 4,
|
||||
ListBeforeExchange: true,
|
||||
SharePrizeList: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listCount, _, _ := client.counts()
|
||||
if listCount != 1 {
|
||||
t.Fatalf("共享列表应只查一次(TTL 内复用),实际 %d 次", listCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunStateClipToDeadline 验证等待时间被裁剪到窗口结束,不会睡过 deadline。
|
||||
func TestRunStateClipToDeadline(t *testing.T) {
|
||||
state := &runState{deadline: time.Now().Add(50 * time.Millisecond)}
|
||||
if got := state.clipToDeadline(10 * time.Millisecond); got != 10*time.Millisecond {
|
||||
t.Fatalf("窗口内等待不应被改动,实际 %v", got)
|
||||
}
|
||||
if got := state.clipToDeadline(time.Second); got <= 0 || got > 60*time.Millisecond {
|
||||
t.Fatalf("超出窗口的等待应被裁剪,实际 %v", got)
|
||||
}
|
||||
if got := (&runState{deadline: time.Now().Add(-time.Millisecond)}).clipToDeadline(time.Second); got != 0 {
|
||||
t.Fatalf("窗口已过应不再等待,实际 %v", got)
|
||||
}
|
||||
if got := (&runState{}).clipToDeadline(time.Second); got != time.Second {
|
||||
t.Fatalf("非窗口模式不应裁剪,实际 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunStateAccountFinishedAndRoundTracking 覆盖独立循环新增的两个判定:
|
||||
// accountFinished(账号自己打完就退出,同时尊重全局目标终止)与最大轮次统计。
|
||||
func TestRunStateAccountFinishedAndRoundTracking(t *testing.T) {
|
||||
state := newRunState([]Account{{UID: 1}}, 2, 1, Config{})
|
||||
if state.accountFinished(1, 2) {
|
||||
t.Fatal("目标都没完成时不应判定账号结束")
|
||||
}
|
||||
state.accounts[1][0].Done = true
|
||||
if state.accountFinished(1, 2) {
|
||||
t.Fatal("还有一个目标未完成时不应判定账号结束")
|
||||
}
|
||||
state.accounts[1][1].Done = true
|
||||
if !state.accountFinished(1, 2) {
|
||||
t.Fatal("所有目标完成后应判定账号结束")
|
||||
}
|
||||
|
||||
// 全局目标终止(售罄 / 下架)后,即使本账号状态未落,也算完成。
|
||||
global := newRunState([]Account{{UID: 2}}, 1, 1, Config{})
|
||||
global.targetDone[0] = true
|
||||
if !global.accountFinished(2, 1) {
|
||||
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 {
|
||||
t.Fatalf("最大轮次=%d, want 7", got)
|
||||
}
|
||||
}
|
||||
+1339
-94
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -481,3 +482,182 @@ func TestRunTargetsDoesNotExchangeSamePrizeTwiceViaNameMatch(t *testing.T) {
|
||||
t.Fatalf("exchangeCount=%d, want 1(同一奖品不应重复兑换)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsSoldOutKeepsProbingUntilSuccess 验证「已抢完」不再默认终止:
|
||||
// 库存可能因为别人取消 / 锁单过期回流,窗口内要继续探测到成功。
|
||||
func TestRunTargetsSoldOutKeepsProbingUntilSuccess(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
calls := 0
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
mu.Lock()
|
||||
calls++
|
||||
current := calls
|
||||
mu.Unlock()
|
||||
if current <= 2 {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "该奖品已抢完"}, nil
|
||||
}
|
||||
return &huya.ScoreExchangePrizeResp{Status: 200, Msg: "请求成功"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 6,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
StopAccountAfterSuccess: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, exchangeCount, _ := client.counts()
|
||||
if exchangeCount != 3 {
|
||||
t.Fatalf("exchangeCount=%d, want 3(售罄后应继续探测直到成功)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsStopOnSoldOutTerminatesTarget 验证显式开启 StopOnSoldOut 时售罄即停。
|
||||
func TestRunTargetsStopOnSoldOutTerminatesTarget(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "该奖品已抢完"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 5,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
StopOnSoldOut: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, exchangeCount, _ := client.counts()
|
||||
if exchangeCount != 1 {
|
||||
t.Fatalf("exchangeCount=%d, want 1(StopOnSoldOut 时售罄即停)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsOffShelfTerminatesTarget 验证下架/不存在仍然直接终止该 target。
|
||||
func TestRunTargetsOffShelfTerminatesTarget(t *testing.T) {
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "奖品已下架"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
|
||||
err := runner.RunTargets(context.Background(), []Account{{UID: 1, Cookie: "yyuid=1"}}, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 4,
|
||||
Delay: time.Millisecond,
|
||||
ErrorBackoff: time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, exchangeCount, _ := client.counts()
|
||||
if exchangeCount != 1 {
|
||||
t.Fatalf("exchangeCount=%d, want 1(下架应终止该 target)", exchangeCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsConcurrencyLimitsInFlightRequests 验证并发额度作用在单次请求上:
|
||||
// 在途请求数不会超过 Concurrency,但多个账号确实能同时在途。
|
||||
func TestRunTargetsConcurrencyLimitsInFlightRequests(t *testing.T) {
|
||||
var inFlight, peak int32
|
||||
client := &fakeActivityClient{
|
||||
exchangeFn: func(uid int64, sid, pid int32) (*huya.ScoreExchangePrizeResp, error) {
|
||||
current := atomic.AddInt32(&inFlight, 1)
|
||||
for {
|
||||
observed := atomic.LoadInt32(&peak)
|
||||
if current <= observed || atomic.CompareAndSwapInt32(&peak, observed, current) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
atomic.AddInt32(&inFlight, -1)
|
||||
return &huya.ScoreExchangePrizeResp{Status: 500, Msg: "操作频繁,请稍后再试"}, nil
|
||||
},
|
||||
}
|
||||
runner := Runner{Client: client}
|
||||
accounts := make([]Account, 0, 6)
|
||||
for uid := int64(1); uid <= 6; uid++ {
|
||||
accounts = append(accounts, Account{UID: uid, Cookie: "yyuid=1"})
|
||||
}
|
||||
|
||||
err := runner.RunTargets(context.Background(), accounts, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 1,
|
||||
Delay: time.Millisecond,
|
||||
Concurrency: 2,
|
||||
TooFrequentBackoff: 10 * time.Millisecond,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := atomic.LoadInt32(&peak); got != 2 {
|
||||
t.Fatalf("peak in-flight=%d, want 2(并发额度应精确限制在途请求数)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunTargetsEmitsSummary 验证任务结束时汇总请求次数与结局分布。
|
||||
func TestRunTargetsEmitsSummary(t *testing.T) {
|
||||
client := &fakeActivityClient{}
|
||||
var summary RunSummary
|
||||
runner := Runner{
|
||||
Client: client,
|
||||
OnSummary: func(item RunSummary) { summary = item },
|
||||
}
|
||||
accounts := []Account{{UID: 1, Cookie: "yyuid=1"}, {UID: 2, Cookie: "yyuid=2"}}
|
||||
|
||||
// 异步刷新只在有 emit 回调时才跑(没地方上报就不发请求),这里给个空回调。
|
||||
err := runner.RunTargets(context.Background(), accounts, []Target{{PID: 12889}}, Config{
|
||||
SID: 2203,
|
||||
Loops: 3,
|
||||
Delay: time.Millisecond,
|
||||
Concurrency: 2,
|
||||
StopAccountAfterSuccess: true,
|
||||
RefreshAfterSuccess: true,
|
||||
}, func(Result) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary.Accounts != len(accounts) || summary.Targets != 1 {
|
||||
t.Fatalf("summary=%+v", summary)
|
||||
}
|
||||
if summary.ExchangeReqs != len(accounts) {
|
||||
t.Fatalf("ExchangeReqs=%d, want %d", summary.ExchangeReqs, len(accounts))
|
||||
}
|
||||
if summary.ScoreReqs != len(accounts) || summary.RecordReqs != len(accounts) {
|
||||
t.Fatalf("刷新请求未计入汇总: score=%d records=%d", summary.ScoreReqs, summary.RecordReqs)
|
||||
}
|
||||
if summary.SuccessUIDs != len(accounts) || summary.Outcomes[CategorySuccess] != len(accounts) {
|
||||
t.Fatalf("成功统计不正确: %+v", summary)
|
||||
}
|
||||
if summary.Duration <= 0 {
|
||||
t.Fatalf("Duration=%v, want > 0", summary.Duration)
|
||||
}
|
||||
}
|
||||
|
||||
// TestJitterDurationAddsUpToQuarter 验证抖动只往上加、最多 25%,且不退化为 0。
|
||||
func TestJitterDurationAddsUpToQuarter(t *testing.T) {
|
||||
base := 400 * time.Millisecond
|
||||
for i := 0; i < 200; i++ {
|
||||
got := jitterDuration(base)
|
||||
if got < base || got > base+base/4 {
|
||||
t.Fatalf("jitterDuration(%v)=%v, want [%v,%v]", base, got, base, base+base/4)
|
||||
}
|
||||
}
|
||||
if got := jitterDuration(0); got != 0 {
|
||||
t.Fatalf("jitterDuration(0)=%v, want 0", got)
|
||||
}
|
||||
if got := jitterDuration(time.Nanosecond); got != time.Nanosecond {
|
||||
t.Fatalf("jitterDuration(1ns)=%v, want 1ns", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package sniper
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
)
|
||||
|
||||
// MinTriggerAdvance 是触发提前量的下限。
|
||||
//
|
||||
// 动态提前量只补偿「请求在途时间 + 时钟误差」,正常情况下就是几十毫秒;
|
||||
// 下限 50ms 是为了在时钟校准异常(误差边界为 0)时仍然留一点余量。
|
||||
const MinTriggerAdvance = 50 * time.Millisecond
|
||||
|
||||
const (
|
||||
// WarmupLead 是预热连接相对开抢时刻的提前量。
|
||||
//
|
||||
// 2 秒足够建连 + 握手(实测单账号建连约 300ms),又不会让连接闲置太久:
|
||||
// 旧实现一启动就预热、然后干等几十分钟,连接是否还活着只能靠运气。
|
||||
WarmupLead = 2 * time.Second
|
||||
// ResyncLead 是「临近复校」相对开抢时刻的提前量。
|
||||
//
|
||||
// 只做一次校准是不够的:pc-1/pc-2/pc-3 三台机器的本机偏移分别是 ≈0 / -370ms / +900ms,
|
||||
// 而且本机时钟在等待期间还会漂移。触发前 3 秒再校准一次,能把这部分误差压掉。
|
||||
ResyncLead = 3 * time.Second
|
||||
)
|
||||
|
||||
// TriggerPlan 描述一次定时抢购的关键时刻(全部是「本机时钟」下的时刻)。
|
||||
type TriggerPlan struct {
|
||||
// Advance 是相对开抢时刻的提前量(含 RTT/2 与时钟误差补偿)。
|
||||
Advance time.Duration
|
||||
// OpenAt 是开抢时刻换算到本机时钟后的时刻。
|
||||
OpenAt time.Time
|
||||
// WarmupAt 是应当开始预热连接的时刻。
|
||||
WarmupAt time.Time
|
||||
// ResyncAt 是应当复校服务端时钟的时刻。
|
||||
ResyncAt time.Time
|
||||
// TriggerAt 是应当开始发请求的时刻。
|
||||
TriggerAt time.Time
|
||||
// WindowEnd 是抢购窗口结束时刻。
|
||||
WindowEnd time.Time
|
||||
}
|
||||
|
||||
// PlanTrigger 计算定时抢购的预热 / 复校 / 触发 / 窗口结束时刻。
|
||||
//
|
||||
// target 是界面上填写的时间,按「服务端时间」理解;offset 是「服务端 - 本机」的偏差。
|
||||
// advance 默认取 calibration.ErrorBound + calibration.RTT/2(参考 dygou_go 的
|
||||
// dynamicAdvance):固定 2500ms 的提前量既浪费又伤身——2026-10-16 实测,开抢前那 2.5 秒
|
||||
// 打出去的请求全部被「活动太火爆」挡回,等于先把账号的令牌桶烧掉。
|
||||
// overrideLead > 0 时沿用旧行为(兼容界面里显式填写的提前量)。
|
||||
func PlanTrigger(target time.Time, calibration huya.TimeCalibration, overrideLead time.Duration, window time.Duration) TriggerPlan {
|
||||
advance := overrideLead
|
||||
if advance <= 0 {
|
||||
advance = calibration.ErrorBound + calibration.RTT/2
|
||||
if advance < MinTriggerAdvance {
|
||||
advance = MinTriggerAdvance
|
||||
}
|
||||
}
|
||||
if window <= 0 {
|
||||
window = DefaultWindowSeconds * time.Second
|
||||
}
|
||||
openAt := target.Add(-calibration.Offset)
|
||||
return TriggerPlan{
|
||||
Advance: advance,
|
||||
OpenAt: openAt,
|
||||
WarmupAt: openAt.Add(-WarmupLead),
|
||||
ResyncAt: openAt.Add(-ResyncLead),
|
||||
TriggerAt: openAt.Add(-advance),
|
||||
WindowEnd: openAt.Add(window),
|
||||
}
|
||||
}
|
||||
|
||||
// WindowDuration 把「窗口秒数」配置换算成时长;<=0 时取默认值。
|
||||
func WindowDuration(seconds int) time.Duration {
|
||||
if seconds <= 0 {
|
||||
return DefaultWindowSeconds * time.Second
|
||||
}
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
@@ -5,10 +5,10 @@ package version
|
||||
//
|
||||
// 构建时可用 ldflags 覆盖(构建脚本就是这么做的):
|
||||
//
|
||||
// go build -ldflags "-X huya-go/internal/version.Version=0.2.1"
|
||||
var Version = "0.2.1"
|
||||
// go build -ldflags "-X huya-go/internal/version.Version=0.4.1"
|
||||
var Version = "0.4.1"
|
||||
|
||||
// Display 返回带 v 前缀的展示版本号,例如 v0.2.1。
|
||||
// Display 返回带 v 前缀的展示版本号,例如 v0.4.1。
|
||||
func Display() string {
|
||||
return "v" + Version
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@ package wup
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"huya-go/internal/taf"
|
||||
)
|
||||
@@ -261,3 +264,88 @@ func NormalizePayload(data []byte) []byte {
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// 诊断串里的取值上限:服务端错误信息可能很长,日志里只需要够判断原因的前缀。
|
||||
const (
|
||||
diagnoseValueLimit = 80
|
||||
diagnoseFieldLimit = 6
|
||||
)
|
||||
|
||||
// Diagnose 汇总一次 WUP 响应里可用于排障的字段。
|
||||
//
|
||||
// 「响应缺少 tRsp/tResp」这种报错过去只有一句文案,服务端的 iRet / status /
|
||||
// context 全被丢掉,事后只能靠抓包复现(2026-10-16 pc-3 日志里同一账号连续 13 次
|
||||
// 命中该错误,却看不出任何原因)。这里把 tag3(iRet)、tag9(context)、tag10(status)
|
||||
// 与 tResp 数据体的 key 一并带出来,一次日志就能定性。
|
||||
func (r *Response) Diagnose() string {
|
||||
if r == nil {
|
||||
return "响应为空"
|
||||
}
|
||||
parts := []string{fmt.Sprintf("iRet=%d", r.Message)}
|
||||
if r.Servant != "" || r.Func != "" {
|
||||
parts = append(parts, fmt.Sprintf("servant=%s.%s", r.Servant, r.Func))
|
||||
}
|
||||
if text := formatDiagnoseMap(r.Status); text != "" {
|
||||
parts = append(parts, "status="+text)
|
||||
}
|
||||
if text := formatDiagnoseMap(r.Context); text != "" {
|
||||
parts = append(parts, "context="+text)
|
||||
}
|
||||
if len(r.NewData) == 0 {
|
||||
parts = append(parts, "keys=空")
|
||||
} else {
|
||||
parts = append(parts, "keys="+formatDiagnoseKeys(r.NewData))
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("payload=%dB", len(r.Buffer)))
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// formatDiagnoseMap 按键名排序输出 map,值过长时截断,保证日志稳定且不刷屏。
|
||||
func formatDiagnoseMap(values map[string]string) string {
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, 0, len(keys))
|
||||
for index, key := range keys {
|
||||
if index >= diagnoseFieldLimit {
|
||||
parts = append(parts, fmt.Sprintf("…(共%d项)", len(keys)))
|
||||
break
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s=%s", key, truncateDiagnoseValue(values[key])))
|
||||
}
|
||||
return "{" + strings.Join(parts, " ") + "}"
|
||||
}
|
||||
|
||||
// formatDiagnoseKeys 输出 tResp 数据体的键名(值可能是任意结构,只列键)。
|
||||
func formatDiagnoseKeys(values map[string][]byte) string {
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
keys = append(keys, fmt.Sprintf("%s(%dB)", key, len(values[key])))
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return "{" + strings.Join(keys, " ") + "}"
|
||||
}
|
||||
|
||||
func truncateDiagnoseValue(value string) string {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
if len(trimmed) <= diagnoseValueLimit {
|
||||
return trimmed
|
||||
}
|
||||
return trimmed[:diagnoseValueLimit] + "…"
|
||||
}
|
||||
|
||||
// HexHead 把二进制帧的前 n 字节转成十六进制,用于 debug 级日志定位协议问题。
|
||||
func HexHead(data []byte, n int) string {
|
||||
if n <= 0 || len(data) == 0 {
|
||||
return ""
|
||||
}
|
||||
if n > len(data) {
|
||||
n = len(data)
|
||||
}
|
||||
return hex.EncodeToString(data[:n])
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package wup_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"huya-go/internal/huya"
|
||||
@@ -31,3 +32,56 @@ func TestWupEncodeDecodeHeader(t *testing.T) {
|
||||
t.Fatal("missing tReq")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResponseDiagnoseIncludesServerFields 验证诊断串会把 WUP 响应里的排障字段带出来。
|
||||
//
|
||||
// 2026-10-16 的复盘卡在「响应缺少 tRsp/tResp」只有一句文案:服务端回的 iRet、
|
||||
// status、context 与数据体键名全被丢掉,同一账号连续 13 次命中也无法定性。
|
||||
func TestResponseDiagnoseIncludesServerFields(t *testing.T) {
|
||||
resp := &wup.Response{
|
||||
Message: -1,
|
||||
Servant: "webActUI",
|
||||
Func: "scoreExchangePrize",
|
||||
Status: map[string]string{"STATUS_RESULT_DESC": "风控拦截", "STATUS_RESULT_CODE": "-1"},
|
||||
Context: map[string]string{"uid": "123"},
|
||||
NewData: map[string][]byte{"tErr": {0x0c}},
|
||||
Buffer: []byte{1, 2, 3},
|
||||
}
|
||||
got := resp.Diagnose()
|
||||
for _, want := range []string{
|
||||
"iRet=-1",
|
||||
"servant=webActUI.scoreExchangePrize",
|
||||
"STATUS_RESULT_CODE=-1",
|
||||
"STATUS_RESULT_DESC=风控拦截",
|
||||
"context={uid=123}",
|
||||
"keys={tErr(1B)}",
|
||||
"payload=3B",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("Diagnose()=%q,缺少 %q", got, want)
|
||||
}
|
||||
}
|
||||
if got := (*wup.Response)(nil).Diagnose(); got != "响应为空" {
|
||||
t.Fatalf("空响应诊断=%q", got)
|
||||
}
|
||||
if got := (&wup.Response{}).Diagnose(); !strings.Contains(got, "iRet=0") || !strings.Contains(got, "keys=空") {
|
||||
t.Fatalf("零值响应诊断=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHexHead 验证原始帧前缀输出的截断与边界。
|
||||
func TestHexHead(t *testing.T) {
|
||||
data := []byte{0x1f, 0x8b, 0x08, 0x00}
|
||||
if got := wup.HexHead(data, 2); got != "1f8b" {
|
||||
t.Fatalf("HexHead(2)=%q", got)
|
||||
}
|
||||
if got := wup.HexHead(data, 32); got != "1f8b0800" {
|
||||
t.Fatalf("HexHead 越界应截断到实际长度: %q", got)
|
||||
}
|
||||
if got := wup.HexHead(nil, 8); got != "" {
|
||||
t.Fatalf("空数据=%q", got)
|
||||
}
|
||||
if got := wup.HexHead(data, 0); got != "" {
|
||||
t.Fatalf("长度为 0=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
"info": {
|
||||
"companyName": "huya-go",
|
||||
"productName": "虎牙抢购助手",
|
||||
"productVersion": "0.2.1",
|
||||
"productVersion": "0.4.1",
|
||||
"copyright": "",
|
||||
"comments": "虎牙活动积分兑换/抢购工具"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user