feat: 优化代理准备并完善远端部署
- 增加严格代理、两分钟预取、白名单去重与分组状态展示\n- 增加远端注册令牌和安全地址校验\n- 增加 Docker Compose、Caddy 示例与控制中心部署文档
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.github
|
||||
build
|
||||
frontend
|
||||
docs
|
||||
work
|
||||
logs
|
||||
*.log
|
||||
deploy/control-center/.env
|
||||
deploy/control-center/data
|
||||
@@ -28,3 +28,9 @@ Runtime data, cookies, account files, logs, `config.json`, and fonts must remain
|
||||
|
||||
## Agent-Specific Instructions
|
||||
Do not launch browsers or browser automation for UI validation unless explicitly requested. Use type checks, builds, and existing tests.
|
||||
|
||||
## Remote Control Documentation
|
||||
`docs/远程控制.md` is the source of truth for the optional remote-control system. Any change to `internal/remote/`, `cmd/douyu-control/`, remote settings, remote Web UI, enrollment/token behavior, command protocol, log formats, exports, or control-center storage must update that document in the same change.
|
||||
|
||||
## Proxy Documentation
|
||||
`docs/代理池与白名单.md` is the source of truth for proxy extraction, whitelist handling, account grouping, standby proxies, runtime failover, and proxy scheduling. Any change to `internal/proxy/`, `internal/seckill/proxy_groups.go`, proxy timing/settings, or proxy logs/statistics must update that document in the same change.
|
||||
|
||||
@@ -59,13 +59,19 @@ GOOS=linux GOARCH=amd64 wails build
|
||||
| `DOUYU_CONTROL_ADDR` | 远端控制台监听地址 | `:18080` |
|
||||
| `DOUYU_CONTROL_DATA` | 远端控制台数据目录 | `remote-data` |
|
||||
| `DOUYU_CONTROL_OPERATOR_TOKEN` | 网页控制台令牌 | 启动时随机生成 |
|
||||
| `DOUYU_CONTROL_ENROLL_TOKEN` | 可选的新实例注册口令 | 空 |
|
||||
| `DOUYU_CONTROL_ENROLL_TOKEN` | 新实例注册令牌 | 空 |
|
||||
| `DOUYU_CONTROL_ENROLL_WINDOW` | 无注册口令时的自动注册窗口 | `10m` |
|
||||
|
||||
## 远端控制(可选)
|
||||
|
||||
远端控制不参与本地定时、代理准备、锁单和支付链路。网络中断时实例继续本地抢购,事件写入本地缓冲后可重连补传。
|
||||
|
||||
完整设计与维护说明见 [docs/远程控制.md](docs/远程控制.md)。
|
||||
|
||||
代理池、白名单、备用代理和故障回退的当前实现与待讨论方案见 [docs/代理池与白名单.md](docs/代理池与白名单.md)。
|
||||
|
||||
代理默认启用严格模式:定时任务提前 2 分钟准备,代理未就绪时不启动且不回退直连;品赞提取强制 JSON,同机多实例共享白名单协调锁,主界面直接显示 `G1`、`G2` 或“直连”。
|
||||
|
||||
构建并启动控制中心:
|
||||
|
||||
```bash
|
||||
@@ -73,11 +79,15 @@ GOOS=linux GOARCH=amd64 wails build
|
||||
./build/bin/douyu-control -addr :18080 -data ./remote-data
|
||||
```
|
||||
|
||||
程序会打印一个带自动登录信息的管理链接。桌面端在“设置 -> 远端控制”中只需要填写控制中心地址,实例首次连接会自动注册并把独立令牌保存在本机。默认自动注册窗口为控制中心启动后的 10 分钟,窗口关闭后不再接受新实例。
|
||||
程序会打印一个带自动登录信息的管理链接。桌面端在“设置 -> 远端控制”中填写控制中心地址和注册令牌,实例首次连接会换取独立令牌并保存在本机。
|
||||
|
||||
桌面端只填写根地址,例如 `https://control.example.com`,不要带 `/#admin=...` 或子路径。
|
||||
|
||||
公网部署使用 [deploy/control-center](deploy/control-center/README.md) 中的 Docker Compose 和 Caddy 示例。容器只监听回环地址,HTTPS 由宿主机现有 Caddy 终止。
|
||||
|
||||
说明:
|
||||
|
||||
- 实例主动通过 WebSocket 外连并自动注册,不需要为每台抢购电脑开放入站端口,也不需要手工配置实例令牌。
|
||||
- 实例主动通过 WebSocket 外连并自动注册,不需要为每台抢购电脑开放入站端口,也不需要手工配置实例令牌;只需填写控制中心地址和统一注册令牌。
|
||||
- 控制台按 `machineId` 动态聚合任意数量的实例,可查看机器、实例、运行结果和实时结构化日志;不假定固定实例数。
|
||||
- 当前支持远端刷新状态、停止抢购和取消定时;启动/定时任务仍以本地配置为准。
|
||||
- Cookie、CSRF、代理密码、白名单签名密钥和 Trace 正文不会上传。
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# 发布到镜像仓库后改为固定版本镜像,例如 ghcr.io/owner/douyu-control:v1.0.0
|
||||
DOUYU_CONTROL_IMAGE=douyu-control:local
|
||||
|
||||
# 中国大陆服务器可使用 https://goproxy.cn,direct
|
||||
GOPROXY=https://proxy.golang.org,direct
|
||||
|
||||
# 宿主机只监听回环地址,由 Caddy 暴露 HTTPS。
|
||||
DOUYU_CONTROL_HOST_PORT=18080
|
||||
|
||||
# 管理网页令牌,与注册令牌必须不同。
|
||||
DOUYU_CONTROL_OPERATOR_TOKEN=replace-with-openssl-rand-hex-32
|
||||
|
||||
# 桌面端“注册令牌”填写同一个值。
|
||||
DOUYU_CONTROL_ENROLL_TOKEN=replace-with-another-openssl-rand-hex-32
|
||||
|
||||
# 仅在未设置注册令牌时启用自动注册窗口。
|
||||
DOUYU_CONTROL_ENROLL_WINDOW=10m
|
||||
@@ -0,0 +1,2 @@
|
||||
.env
|
||||
data/
|
||||
@@ -0,0 +1,14 @@
|
||||
control.example.com {
|
||||
encode zstd gzip
|
||||
|
||||
reverse_proxy 127.0.0.1:18080 {
|
||||
flush_interval -1
|
||||
}
|
||||
|
||||
header {
|
||||
Strict-Transport-Security "max-age=31536000"
|
||||
Referrer-Policy "no-referrer"
|
||||
X-Content-Type-Options "nosniff"
|
||||
X-Frame-Options "DENY"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM golang:1.26-alpine AS build
|
||||
|
||||
ARG TARGETOS=linux
|
||||
ARG TARGETARCH=amd64
|
||||
ARG GOPROXY=https://proxy.golang.org,direct
|
||||
|
||||
ENV GOPROXY=${GOPROXY}
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download github.com/gorilla/websocket
|
||||
|
||||
COPY internal ./internal
|
||||
COPY cmd/douyu-control ./cmd/douyu-control
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} \
|
||||
go build -trimpath -ldflags="-s -w" -o /out/douyu-control ./cmd/douyu-control
|
||||
|
||||
FROM alpine:3.22
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata \
|
||||
&& addgroup -S -g 10001 douyu \
|
||||
&& adduser -S -D -H -u 10001 -G douyu douyu \
|
||||
&& mkdir -p /data \
|
||||
&& chown douyu:douyu /data \
|
||||
&& chmod 0700 /data
|
||||
|
||||
ENV TZ=Asia/Shanghai \
|
||||
DOUYU_CONTROL_ADDR=:18080 \
|
||||
DOUYU_CONTROL_DATA=/data
|
||||
|
||||
COPY --from=build /out/douyu-control /usr/local/bin/douyu-control
|
||||
|
||||
USER 10001:10001
|
||||
|
||||
EXPOSE 18080
|
||||
VOLUME ["/data"]
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget -qO- http://127.0.0.1:18080/api/health >/dev/null || exit 1
|
||||
|
||||
ENTRYPOINT ["douyu-control"]
|
||||
@@ -0,0 +1,109 @@
|
||||
# 远端控制中心部署
|
||||
|
||||
该目录只包含控制中心的部署文件。Go 源码仍位于仓库的 `cmd/douyu-control` 和 `internal/remote`,避免桌面端 Agent 与控制中心协议分叉。
|
||||
|
||||
## 架构
|
||||
|
||||
```text
|
||||
Internet
|
||||
-> Caddy 443
|
||||
-> 127.0.0.1:18080
|
||||
-> douyu-control 容器
|
||||
-> ./data
|
||||
```
|
||||
|
||||
Caddy 不放入该 Compose。继续使用宿主机现有 Caddy,避免重复申请证书和占用 80/443。
|
||||
|
||||
## 首次部署
|
||||
|
||||
```bash
|
||||
cd deploy/control-center
|
||||
cp .env.example .env
|
||||
openssl rand -hex 32
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
把两个随机值分别填入 `.env`:
|
||||
|
||||
```text
|
||||
DOUYU_CONTROL_OPERATOR_TOKEN=管理网页令牌
|
||||
DOUYU_CONTROL_ENROLL_TOKEN=桌面实例注册令牌
|
||||
```
|
||||
|
||||
创建数据目录并交给容器用户:
|
||||
|
||||
```bash
|
||||
sudo install -d -m 0700 -o 10001 -g 10001 data
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
如果服务器无法访问 `proxy.golang.org`,将 `.env` 中的 `GOPROXY` 改为可用的 Go 模块代理,例如 `https://goproxy.cn,direct`。
|
||||
|
||||
检查:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:18080/api/health
|
||||
docker compose ps
|
||||
docker compose logs -f --tail=100
|
||||
```
|
||||
|
||||
## Caddy
|
||||
|
||||
把 `Caddyfile.example` 中的配置改好域名后加入宿主机现有 Caddy 站点配置,然后验证并重载:
|
||||
|
||||
```bash
|
||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
sudo systemctl reload caddy
|
||||
```
|
||||
|
||||
公网防火墙只开放 `80/443`,不要开放 `18080`。Caddy 会自动处理 HTTPS 和 Agent WebSocket Upgrade。
|
||||
|
||||
## 桌面实例
|
||||
|
||||
每个实例填写:
|
||||
|
||||
```text
|
||||
控制中心地址: https://control.example.com
|
||||
注册令牌: 与 DOUYU_CONTROL_ENROLL_TOKEN 相同
|
||||
```
|
||||
|
||||
实例首次连接时使用注册令牌换取独立实例令牌,之后复用本机凭据。控制中心不需要保存桌面端的注册令牌。
|
||||
|
||||
## 管理网页
|
||||
|
||||
```text
|
||||
https://control.example.com/#admin=<DOUYU_CONTROL_OPERATOR_TOKEN>
|
||||
```
|
||||
|
||||
`#admin` 不会发送给服务器,页面读取后会从地址栏移除。
|
||||
|
||||
## 数据与备份
|
||||
|
||||
```text
|
||||
data/
|
||||
events.ndjson
|
||||
runs.ndjson
|
||||
agent_tokens.json
|
||||
```
|
||||
|
||||
`agent_tokens.json` 丢失后,已有实例需要重新注册。至少每天备份一次整个 `data` 目录。
|
||||
|
||||
当前 NDJSON 不会自动轮转。长期运行前需要增加应用层保留策略,不能只依赖 Docker 容器日志轮转。
|
||||
|
||||
## 升级
|
||||
|
||||
使用本地构建:
|
||||
|
||||
```bash
|
||||
docker compose build --pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
使用镜像仓库时,将 `.env` 中的 `DOUYU_CONTROL_IMAGE` 改为固定版本,然后:
|
||||
|
||||
```bash
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
升级不会删除 `data`。控制中心只能运行一个副本,不能直接水平扩容。
|
||||
@@ -0,0 +1,34 @@
|
||||
name: douyu-control
|
||||
|
||||
services:
|
||||
control-center:
|
||||
image: ${DOUYU_CONTROL_IMAGE:-douyu-control:local}
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: deploy/control-center/Dockerfile
|
||||
args:
|
||||
GOPROXY: ${GOPROXY:-https://proxy.golang.org,direct}
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
DOUYU_CONTROL_ADDR: ":18080"
|
||||
DOUYU_CONTROL_DATA: "/data"
|
||||
TZ: "Asia/Shanghai"
|
||||
ports:
|
||||
- "127.0.0.1:${DOUYU_CONTROL_HOST_PORT:-18080}:18080"
|
||||
volumes:
|
||||
- ./data:/data
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
stop_grace_period: 20s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "20m"
|
||||
max-file: "3"
|
||||
+647
@@ -0,0 +1,647 @@
|
||||
# 代理池与白名单
|
||||
|
||||
本文档是斗鱼抢购系统代理池、动态提取、白名单、账号分组、备用代理和故障回退功能的分析与维护入口。
|
||||
|
||||
任何涉及以下内容的修改,都必须在同一变更中同步更新本文档:
|
||||
|
||||
- `internal/proxy/`
|
||||
- `internal/seckill/proxy_groups.go`
|
||||
- 定时代理准备和立即抢购代理准备
|
||||
- 白名单添加、代理提取、代理校验
|
||||
- 账号分组、备用代理、故障切换
|
||||
- 代理相关配置和共享配置
|
||||
- 代理池演练
|
||||
- 代理日志、统计和故障结论
|
||||
|
||||
## 1. 优先级
|
||||
|
||||
本地抢购始终优先。
|
||||
|
||||
- 代理功能不能依赖远端控制中心。
|
||||
- 远端网络中断不能影响代理准备和本地抢购。
|
||||
- 代理后台失败允许回退,但回退策略属于抢购策略的一部分,必须单独评审。
|
||||
- 代理日志应能准确说明实际使用的是代理还是直连。
|
||||
|
||||
## 2. 当前总体流程
|
||||
|
||||
```text
|
||||
读取代理配置
|
||||
↓
|
||||
按账号数量分组
|
||||
↓
|
||||
计算活动代理和备用代理数量
|
||||
↓
|
||||
调用代理提取 API
|
||||
↓
|
||||
必要时添加/校验白名单
|
||||
↓
|
||||
校验代理出口和延迟
|
||||
↓
|
||||
账号绑定代理客户端
|
||||
↓
|
||||
运行期间监控代理传输故障
|
||||
↓
|
||||
优先切换备用代理
|
||||
↓
|
||||
无备用代理时切换直连
|
||||
```
|
||||
|
||||
定时抢购和立即抢购使用同一套分组逻辑,但准备时间和超时不同。
|
||||
|
||||
## 3. 主要代码
|
||||
|
||||
| 路径 | 职责 |
|
||||
|---|---|
|
||||
| `internal/proxy/service.go` | 代理平台抽象、提取、自动白名单 |
|
||||
| `internal/proxy/ipzan.go` | 品赞 API、白名单签名和响应解析 |
|
||||
| `internal/proxy/generic.go` | 通用代理 API 和文本格式解析 |
|
||||
| `internal/client/proxy.go` | 代理 URL、HTTP 客户端和连接错误处理 |
|
||||
| `internal/client/proxy_health.go` | 传输故障监控回调 |
|
||||
| `internal/client/proxy_probe.go` | 代理只读探测 |
|
||||
| `internal/seckill/proxy_groups.go` | 分组、提取、校验、备用、故障切换 |
|
||||
| `internal/seckill/scheduler.go` | 抢购主流程和代理准备入口 |
|
||||
| `internal/seckill/schedule_timer.go` | 定时任务触发前的代理准备 |
|
||||
| `internal/app/app_proxy.go` | 手动提取和启动时刷新 |
|
||||
| `internal/app/app_proxy_drill.go` | 代理池演练 |
|
||||
| `internal/app/app_shared_proxy_config.go` | 跨实例加载/保存共享代理配置 |
|
||||
| `frontend/src/components/modal/SettingsModal.vue` | 桌面端代理设置和演练界面 |
|
||||
|
||||
## 4. 配置
|
||||
|
||||
主要配置字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `proxyEnabled` | 是否启用代理 |
|
||||
| `proxyRequired` | 严格代理模式:代理未就绪时不启动,也不自动回退直连 |
|
||||
| `proxyUrl` | 当前静态代理地址 |
|
||||
| `proxyApi` | 动态代理提取 API |
|
||||
| `proxyExpiresAt` | 当前静态代理过期时间 |
|
||||
| `autoFetchProxyOnSchedule` | 定时抢购前自动提取代理 |
|
||||
| `accountsPerProxy` | 每个活动代理承载的账号数 |
|
||||
| `proxySparePercent` | 备用代理比例 |
|
||||
| `proxyAutoWhitelist` | 提取前自动添加白名单 |
|
||||
| `proxyWhitelistReplace` | 白名单满时替换最早 IP |
|
||||
| `proxyWhitelistPassword` | 品赞登录密码 |
|
||||
| `proxyWhitelistSignKey` | 品赞 AES 签名密钥 |
|
||||
|
||||
默认值:
|
||||
|
||||
```text
|
||||
账号/组 = 5
|
||||
备用比例 = 50%(最低 50%)
|
||||
严格代理模式 = 开启
|
||||
```
|
||||
|
||||
备用代理数量按活动代理数量向上取整,至少为 1:
|
||||
|
||||
```text
|
||||
备用数量 = ceil(活动代理数 × 备用比例 / 100)
|
||||
```
|
||||
|
||||
因此 4 个活动代理默认有 2 个备用代理。
|
||||
|
||||
## 5. 共享代理配置
|
||||
|
||||
共享配置用于让同一台电脑或一组电脑使用相同代理参数。
|
||||
|
||||
共享文件不保存:
|
||||
|
||||
- 当前运行时代理 URL
|
||||
- 当前代理过期时间
|
||||
- 账号或 Cookie
|
||||
|
||||
共享文件当前包含:
|
||||
|
||||
- 代理启用状态
|
||||
- 严格代理模式
|
||||
- 代理提取 API
|
||||
- 账号分组
|
||||
- 备用比例
|
||||
- 定时预取
|
||||
- 自动白名单
|
||||
- 白名单密码和签名密钥
|
||||
- 远端控制配置
|
||||
|
||||
共享文件可能包含敏感凭据,权限必须限制为仅当前用户可读写。
|
||||
|
||||
## 6. 代理提取
|
||||
|
||||
支持的来源:
|
||||
|
||||
1. 动态提取 API。
|
||||
2. 一个或多个静态代理。
|
||||
3. 动态代理不足时回退静态代理。
|
||||
|
||||
品赞代理返回格式必须是 JSON。
|
||||
|
||||
只有 JSON 才能保留每个代理的独立用户名和密码。TXT 通常只返回 `IP:端口`,会丢失代理认证信息,实际连接时容易出现 `407 Proxy Authentication Required`。
|
||||
|
||||
因此:
|
||||
|
||||
- 品赞控制台中的提取格式应选择 JSON。
|
||||
- 程序对所有品赞提取请求都会强制使用 `format=json`,包括账号密码模式和普通模式。
|
||||
- 手工粘贴或修改提取 API 时,不得改回 TXT。
|
||||
- 静态 HTTP 代理如果带账号密码,也必须保留完整的 `http://user:pass@ip:port` 格式。
|
||||
|
||||
提取流程:
|
||||
|
||||
1. 计算活动代理数量和备用目标。
|
||||
2. 调用动态 API。
|
||||
3. 去重。
|
||||
4. 校验未过期。
|
||||
5. 通过只读接口验证代理。
|
||||
6. 验证失败则继续轮次提取。
|
||||
7. 动态代理不足时尝试静态代理。
|
||||
|
||||
当前常量:
|
||||
|
||||
```text
|
||||
提取基础轮次 = 3
|
||||
最大轮次 = 20
|
||||
提取重试间隔 = 1200ms
|
||||
单次请求超时 = 15s
|
||||
代理校验超时 = 3s
|
||||
校验 worker = 3
|
||||
校验尝试次数 = 1
|
||||
```
|
||||
|
||||
## 7. 白名单
|
||||
|
||||
### 当前流程
|
||||
|
||||
品赞启用自动白名单时:
|
||||
|
||||
1. 先尝试提取代理。
|
||||
2. 平台提示当前 IP 不在白名单。
|
||||
3. 从平台错误中读取实际公网 IP。
|
||||
4. 同一台电脑的多个实例通过跨进程文件锁串行处理该 IP。
|
||||
5. 在锁内复用 10 分钟内的成功标记,避免重复添加。
|
||||
6. 无成功标记时先校验白名单;未添加则等待 1.2 秒,避开品赞 1 秒限频。
|
||||
7. 使用登录密码、API secret 和签名密钥生成签名并添加。
|
||||
8. 写入本机成功标记后释放锁,再继续提取代理。
|
||||
|
||||
品赞返回的常见限制:
|
||||
|
||||
```text
|
||||
白名单仅支持1秒访一次
|
||||
访问频率过快,休息一下
|
||||
```
|
||||
|
||||
### 限频处理
|
||||
|
||||
以下消息现在按可重试错误处理,不再中断代理准备:
|
||||
|
||||
```text
|
||||
添加白名单失败: 访问频率过快
|
||||
白名单仅支持1秒访一次
|
||||
提取频率过快
|
||||
```
|
||||
|
||||
代理提取重试间隔已调整为 1.2 秒。定时任务会在 `T-120s` 开始准备,并持续重试到 `T-15s`,为限频恢复留出窗口。
|
||||
|
||||
## 8. 账号分组
|
||||
|
||||
账号按名称排序后顺序分组,保证相同账号集合尽量得到稳定分组。
|
||||
|
||||
例如:
|
||||
|
||||
```text
|
||||
20 个账号,每组 5 个
|
||||
→ 4 个活动代理组
|
||||
→ 默认 2 个备用代理
|
||||
```
|
||||
|
||||
每个活动组使用独立 HTTP 客户端;同组账号共享一个代理出口。
|
||||
|
||||
## 9. 代理状态可视化
|
||||
|
||||
### 目标
|
||||
|
||||
主界面必须直接显示当前实例的代理准备状态,以及每个账号实际属于哪个代理组,不能要求用户分析抢购日志。
|
||||
|
||||
需要同时覆盖:
|
||||
|
||||
- 桌面端当前实例主界面。
|
||||
- 远端 Web 控制台中的每个实例。
|
||||
- 代理池准备阶段。
|
||||
- 抢购运行阶段。
|
||||
- 备用切换和直连回退之后。
|
||||
|
||||
### 当前实现
|
||||
|
||||
调度器现在维护结构化代理状态,不再要求前端解析日志:
|
||||
|
||||
```text
|
||||
ProxyStatusView
|
||||
enabled / required / state
|
||||
activeCount / standbyCount / standbyTarget / directCount
|
||||
lastError / updatedAt
|
||||
groups[]
|
||||
accounts[]
|
||||
```
|
||||
|
||||
状态值:
|
||||
|
||||
```text
|
||||
disabled 代理未启用
|
||||
empty 尚未准备
|
||||
preparing 正在提取、加白名单或校验
|
||||
ready 活动代理和备用代理达到目标
|
||||
degraded 代理仍可用,但备用不足或存在失败组
|
||||
failed 准备失败或严格模式阻止运行
|
||||
direct_fallback 非严格模式已回退直连
|
||||
stale 配置已变更,等待重新准备
|
||||
```
|
||||
|
||||
代理组和账号映射都来自运行时结构:
|
||||
|
||||
- 组号、账号数、账号列表。
|
||||
- 脱敏后的出口、地区、RTT。
|
||||
- 使用中、失败或直连状态。
|
||||
- 切换次数和最近错误。
|
||||
- 每个账号当前是 `G1`、`G2`、`直连` 还是未分配。
|
||||
|
||||
### 主界面
|
||||
|
||||
主界面新增代理状态条,显示:
|
||||
|
||||
```text
|
||||
活动 4 · 备用 2/2 · 直连 0
|
||||
G1 5号 · G2 5号 · G3 5号 · G4 5号
|
||||
```
|
||||
|
||||
账号作战表新增“代理”列。每组直接显示 `G1`、`G2` 等标签,直连显示红色“直连”,悬停可查看脱敏出口。
|
||||
|
||||
准备中、降级、失败、直连回退和配置变更都有独立状态文案。严格代理模式就绪时会明确显示“严格代理已就绪”。
|
||||
|
||||
### 远端展示
|
||||
|
||||
每个实例行显示活动、备用和直连数量。“代理”按钮可展开当前分组、出口、地区、RTT、切换次数和错误。
|
||||
|
||||
Agent 通过结构化 `proxyStatus` 上报,桌面端通过 `GetProxyStatus` 读取;两条链路使用同一个 `ProxyStatusView`。
|
||||
|
||||
### 更新时点
|
||||
|
||||
状态会在以下时点更新:
|
||||
|
||||
- 开始代理准备。
|
||||
- 分组和校验完成。
|
||||
- 账号绑定完成。
|
||||
- 代理传输异常。
|
||||
- 切换备用代理。
|
||||
- 回退直连。
|
||||
- 补提取成功并重新绑定失败组。
|
||||
- 配置变更。
|
||||
|
||||
代理 URL 只暴露脱敏结果,不包含用户名和密码。
|
||||
|
||||
## 10. 代理校验
|
||||
|
||||
当前校验使用只读接口,不会:
|
||||
|
||||
- 读取 Cookie
|
||||
- 锁单
|
||||
- 支付
|
||||
- 消耗积分
|
||||
|
||||
校验内容:
|
||||
|
||||
- 代理是否可连接
|
||||
- 出口是否可用
|
||||
- 返回延迟
|
||||
- 接口是否能在超时内完成
|
||||
|
||||
校验成功不代表代理在抢购瞬间一定稳定。2026-11-21 的日志显示,代理在 17:59:32 左右获取并校验成功,18:00:06 左右仍发生了集中传输故障。
|
||||
|
||||
## 11. 定时抢购当前准备时序
|
||||
|
||||
当前代码:
|
||||
|
||||
```text
|
||||
T-120s 开始定时代理准备
|
||||
T-120s 至 T-15s 持续重试白名单、提取和校验
|
||||
T-15s 关闭代理准备窗口
|
||||
T-8s 时间临近复校
|
||||
T-2s 预热
|
||||
T-0s 本地定时触发
|
||||
```
|
||||
|
||||
定时触发前会再次检查严格代理门禁。
|
||||
|
||||
严格模式开启且代理已启用时,即使“定时自动预取”未勾选,也会在 `T-120s` 执行代理准备,避免定时触发时因没有准备记录被门禁直接拦截。普通模式仍按“定时自动预取”开关决定是否提前提取。
|
||||
|
||||
严格代理模式开启时,代理准备失败会:
|
||||
|
||||
1. 清除未完成的代理客户端。
|
||||
2. 标记代理状态为失败。
|
||||
3. 定时触发时阻止抢购并记录原因。
|
||||
4. 不使用直连兜底。
|
||||
|
||||
严格模式关闭时,准备失败仍会记录并回退直连,保证旧策略可继续使用。
|
||||
|
||||
立即抢购会同步准备代理,默认超时 5 秒。准备后同样执行严格代理门禁,失败原因会直接返回界面。
|
||||
|
||||
## 12. 运行期故障切换
|
||||
|
||||
代理健康监控记录传输层错误。
|
||||
|
||||
当前切换规则:
|
||||
|
||||
1. 单次网络异常只计数。
|
||||
2. 同一代理组连续 2 次传输故障才切换。
|
||||
3. 有备用代理时,整组切换到备用代理。
|
||||
4. 严格模式且无备用代理时,该组标记失败并等待补提取,不切直连。
|
||||
5. 非严格模式且无备用代理时,整组切换到直连。
|
||||
6. 补提取成功后会优先重新接回仍在等待的失败组。
|
||||
7. 切换后继续补提取备用代理。
|
||||
|
||||
非严格模式已经主动切换到直连的组,不会在运行中自动切回代理;严格模式保留失败组状态,因此可以在新备用到达后重新绑定。
|
||||
|
||||
## 13. 代理有效期
|
||||
|
||||
当前系统支持:
|
||||
|
||||
- 代理 API 返回的 `expiresAt`
|
||||
- API URL 中的 `minute` 或 `min`
|
||||
- 未提供时默认按 10 分钟估算
|
||||
|
||||
当前用户的实际代理套餐有效期为 10 分钟。
|
||||
|
||||
因此提前 2 分钟准备代理不会导致正常抢购期间过期,但仍应保留至少 5 分钟安全余量。
|
||||
|
||||
## 14. 代理池演练
|
||||
|
||||
代理池演练:
|
||||
|
||||
- 使用只读接口
|
||||
- 不读取账号 CK
|
||||
- 不锁单
|
||||
- 不支付
|
||||
- 不消耗积分
|
||||
- 抢购运行中禁止执行
|
||||
|
||||
演练可模拟账号数,计算活动代理和备用代理数量,并逐个验证代理节点。
|
||||
|
||||
演练通过只说明当前时点可用;不能保证开抢瞬间不会集中故障。
|
||||
|
||||
## 15. 2026-11-21 实测摘要
|
||||
|
||||
日志目录:
|
||||
|
||||
```text
|
||||
/Users/yml/日志/斗鱼/11.21
|
||||
```
|
||||
|
||||
总体:
|
||||
|
||||
```text
|
||||
任务数 = 40
|
||||
账号名额 = 798
|
||||
成功 = 200
|
||||
失败 = 598
|
||||
成功率 = 25.06%
|
||||
```
|
||||
|
||||
失败原因:
|
||||
|
||||
```text
|
||||
活动火爆 = 596
|
||||
点击太快 = 2
|
||||
售罄 = 0
|
||||
登录失效 = 0
|
||||
账号终止 = 0
|
||||
```
|
||||
|
||||
按实际网络路径:
|
||||
|
||||
| 路径 | 实例数 | 账号数 | 成功 |
|
||||
|---|---:|---:|---:|
|
||||
| 代理池成功准备 | 10 | 200 | 200 |
|
||||
| 配置代理但回退直连 | 20 | 398 | 0 |
|
||||
| 明确直连 | 10 | 200 | 0 |
|
||||
|
||||
代理准备和切换:
|
||||
|
||||
```text
|
||||
白名单限频导致代理准备失败 = 20 个实例
|
||||
成功准备代理池 = 10 个实例
|
||||
代理故障切换 = 40 次
|
||||
切换备用代理 = 11 次
|
||||
切换直连 = 29 次
|
||||
备用代理补提取 = 11 次
|
||||
补提取后重新接入失败组 = 0 次
|
||||
```
|
||||
|
||||
结论:
|
||||
|
||||
- 当天成功与“代理池真实准备成功”高度一致。
|
||||
- 直连和代理回退批次当天没有成功锁单。
|
||||
- 主要根因是白名单限频被错误判定为致命错误,不是账号或库存本身。
|
||||
|
||||
## 16. 当前已知限制
|
||||
|
||||
### 备用数量不足
|
||||
|
||||
默认 50% 时,4 个活动代理只有 2 个备用代理,无法覆盖 4 个代理同时故障。
|
||||
|
||||
备用不足时严格模式会让失败组等待补提取,但抢购窗口不会因为等待代理而延长。
|
||||
|
||||
### 远端白名单协调尚未实现
|
||||
|
||||
同一台电脑内的多实例白名单已通过跨进程锁和成功标记去重。
|
||||
|
||||
跨机器的全局白名单队列仍待远端控制中心实现;当前每台机器仍独立处理自己的公网 IP。
|
||||
|
||||
### 日志标签可能误导
|
||||
|
||||
代理失败回退直连后,网络统计仍可能显示为“代理组1”,不能仅凭统计组名判断真实出口。
|
||||
|
||||
界面已经使用结构化状态显示真实出口;基于历史日志的导出统计仍需继续补齐真实网络路径字段。
|
||||
|
||||
## 17. 待讨论方案
|
||||
|
||||
以下保留已落地结论和仍待实现的事项。
|
||||
|
||||
### A. 提前 2 分钟准备(已实现)
|
||||
|
||||
当前行为:
|
||||
|
||||
- `T-120s` 开始代理准备。
|
||||
- `T-15s` 最终关闭代理准备窗口。
|
||||
- 中间持续重试白名单、提取和校验。
|
||||
- 立即抢购在启动前同步准备,默认超时 5 秒。
|
||||
|
||||
这样可以覆盖 10 分钟代理有效期,并给白名单限频、提取限频和验证失败留下恢复时间。
|
||||
|
||||
### B. 远端控制统一管理白名单(待实现)
|
||||
|
||||
方向已确认:由远端控制中心做白名单的全局管理和调度,而不是让每个实例分别请求品赞。
|
||||
|
||||
推荐采用“远端管理 + 本机兜底”的结构:
|
||||
|
||||
```text
|
||||
远端控制中心
|
||||
├─ 机器公网 IP 状态
|
||||
├─ 全局白名单命令串行队列
|
||||
├─ 1 秒/次限频
|
||||
├─ 每台机器只保留一个有效白名单
|
||||
└─ 白名单状态和最近检查时间
|
||||
↓
|
||||
每台电脑的本地协调层
|
||||
├─ 执行远端下发的幂等白名单命令
|
||||
├─ 使用本机保存的品赞凭据
|
||||
├─ 接收/缓存白名单状态
|
||||
├─ 同一台机器多实例去重
|
||||
├─ 开抢前本地复核
|
||||
└─ 远端不可用时执行本地兜底
|
||||
↓
|
||||
各实例只负责提取自己的代理组
|
||||
```
|
||||
|
||||
远端控制中心应负责:
|
||||
|
||||
- 按 `machineId` 管理,而不是按实例管理。
|
||||
- 收集或探测每台电脑实际公网 IP。
|
||||
- 串行向各机器下发 `ensure_whitelist` 命令。
|
||||
- 等待本机命令回执后再推进队列,保证同一公网 IP 只添加一次。
|
||||
- 显示 ready、pending、failed、expired。
|
||||
- 在计划抢购前更早执行,例如 `T-10min` 或 `T-5min`。
|
||||
|
||||
本地协调层应负责:
|
||||
|
||||
- 同一台电脑多实例共享白名单状态。
|
||||
- `T-2min` 代理准备前确认白名单仍有效。
|
||||
- 远端不可用时使用本地缓存继续。
|
||||
- 必要时执行一次本地幂等兜底,不让远端成为单点故障。
|
||||
- 品赞密码和签名密钥仍只保存在本机,不集中上传控制中心。
|
||||
|
||||
不建议:
|
||||
|
||||
- 每个实例直接请求远端。
|
||||
- 远端在 `T-0s` 才下发白名单命令。
|
||||
- 远端不可用时本地完全无法抢购。
|
||||
- 控制中心收集或保存品赞明文密码和签名密钥。
|
||||
|
||||
白名单属于低频、可提前完成的操作,应该放在代理提取之前,而不是放进最紧张的锁单窗口。
|
||||
|
||||
### C. 白名单限频与同机去重(本地已实现)
|
||||
|
||||
已实现:
|
||||
|
||||
- “访问频率过快”和“1秒访一次”按可重试错误处理。
|
||||
- 提取重试间隔 1.2 秒。
|
||||
- 同一台电脑的多个实例共享跨进程白名单锁。
|
||||
- 添加成功后写入 10 分钟本地标记,兄弟实例直接复用。
|
||||
- 远端不可用不影响本地白名单兜底。
|
||||
|
||||
### D. 严格代理模式(已实现)
|
||||
|
||||
配置项:
|
||||
|
||||
```text
|
||||
proxyRequired = true
|
||||
```
|
||||
|
||||
默认开启。代理未启用时不影响本地直连抢购。
|
||||
|
||||
严格代理模式下:
|
||||
|
||||
- 代理未就绪不启动抢购。
|
||||
- 不自动回退直连。
|
||||
- 运行期无备用代理时该组不改直连,保留失败状态并补提取。
|
||||
- 补提取成功后重新接回代理。
|
||||
- 立即启动和定时触发都执行同一代理门禁。
|
||||
|
||||
仍待产品决策:
|
||||
|
||||
- 是否保留一台“明确直连”实例用于对照。
|
||||
- 运行期等待代理时是否允许超过抢购窗口。
|
||||
|
||||
### E. 备用代理策略
|
||||
|
||||
即使提高到 50%,4 个活动代理也只有 2 个备用,仍不足以覆盖 4 个代理同时故障。
|
||||
|
||||
候选:
|
||||
|
||||
1. 提高备用比例到 100%。
|
||||
2. 保持低备用比例,但失败组等待补提取。
|
||||
3. 将备用代理视为共享资源池,动态分配给故障组。
|
||||
|
||||
需要结合品赞套餐配额和成本决定。
|
||||
|
||||
### F. 失败组重新接回代理(严格模式已实现)
|
||||
|
||||
严格模式不把失败组改绑直连,而是保留失败状态。备用补提取成功后,优先重新绑定这些组。
|
||||
|
||||
### G. 日志区分真实出口(界面已实现,统计待补齐)
|
||||
|
||||
桌面端和远端界面已显示 `G1`、`G2`、`直连`。后续需要让基于历史日志的统计也明确区分:
|
||||
|
||||
```text
|
||||
真实代理
|
||||
代理回退直连
|
||||
明确直连
|
||||
```
|
||||
|
||||
不能继续把回退直连显示为代理组。
|
||||
|
||||
## 18. 推荐实施顺序
|
||||
|
||||
已完成:
|
||||
|
||||
1. 修复白名单限频错误分类。
|
||||
2. 把代理准备提前到 2 分钟。
|
||||
3. 使用 1.2 秒慢重试和同机跨进程去重。
|
||||
4. 增加正式代理状态快照和账号映射。
|
||||
5. 在主界面和远端控制台展示代理组状态。
|
||||
6. 增加严格代理模式并覆盖立即、定时和运行期路径。
|
||||
7. 严格模式下用补提取备用重新接回失败组。
|
||||
|
||||
后续优先级:
|
||||
|
||||
1. 远端统一白名单协调队列。
|
||||
2. 评估 50% 备用是否继续提高,或改为共享备用池。
|
||||
3. 修复历史日志和导出统计中的真实出口标签。
|
||||
4. 根据实际套餐成本决定是否保留明确直连对照实例。
|
||||
|
||||
## 19. 验证要求
|
||||
|
||||
修改代理相关逻辑后至少运行:
|
||||
|
||||
```bash
|
||||
go test ./internal/...
|
||||
go test ./...
|
||||
cd frontend && npm run type-check
|
||||
./build.sh build
|
||||
```
|
||||
|
||||
应覆盖:
|
||||
|
||||
- 白名单限频后重试成功。
|
||||
- 多个实例共享同一公网 IP。
|
||||
- 严格模式下代理失败不启动抢购。
|
||||
- 备用代理切换。
|
||||
- 无备用时不回退直连。
|
||||
- 新备用到达后失败组重新接回代理。
|
||||
- 代理回退直连的真实日志标签。
|
||||
- 代理有效期计算。
|
||||
- 每个账号到代理组的映射。
|
||||
- 备用切换后分组状态更新。
|
||||
- 直连回退后界面不显示为真实代理。
|
||||
- 远端收到的代理状态与桌面端一致。
|
||||
|
||||
## 20. 决策记录
|
||||
|
||||
| 日期 | 结论 | 状态 |
|
||||
|---|---|---|
|
||||
| 2026-11-21 | 本地抢购优先,代理和远端均不得阻塞抢购主链路 | 已确认 |
|
||||
| 2026-11-21 | 10 分钟代理提前 2 分钟准备,并在 T-15s 截止 | 已实现 |
|
||||
| 2026-11-21 | 同一台电脑多实例不应重复添加白名单 | 已实现本机跨进程去重 |
|
||||
| 2026-11-21 | 白名单优先由远端控制中心统一排程和管理,本地保留兜底 | 方向确认,待实现 |
|
||||
| 2026-11-21 | 品赞所有提取请求必须使用 JSON 格式 | 已实现 |
|
||||
| 2026-11-21 | 白名单和提取限频必须按可重试错误处理 | 已实现 |
|
||||
| 2026-11-21 | 严格代理模式和无直连策略需要支持 | 已实现,默认开启 |
|
||||
| 2026-11-21 | 备用代理默认和最低比例调整为 50% | 已实现 |
|
||||
| 2026-11-21 | 50% 备用是否足以覆盖集中故障 | 待评审 |
|
||||
| 2026-11-21 | 主界面必须直接显示实例内各代理组和账号归属,不能依赖日志分析 | 已实现 |
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
# 远端控制与日志汇总
|
||||
|
||||
本文档是斗鱼抢购系统远端控制功能的唯一维护入口。
|
||||
|
||||
任何涉及以下内容的修改,都必须在同一提交中同步更新本文档:
|
||||
|
||||
- `internal/remote/`
|
||||
- `cmd/douyu-control/`
|
||||
- 桌面端远端设置、主界面远端状态
|
||||
- 远端 Web 控制台
|
||||
- 实例注册、令牌、命令协议
|
||||
- 远端日志、运行记录、导出格式
|
||||
- 远端数据目录和部署方式
|
||||
|
||||
## 1. 设计原则
|
||||
|
||||
本地抢购始终拥有最高优先级。
|
||||
|
||||
- 远端控制不参与定时计算、代理准备、锁单、支付和结果核对。
|
||||
- 远端连接失败、服务器宕机或网络中断不能阻塞本地抢购。
|
||||
- 本地定时任务必须在本地触发,不能依赖远端实时发送启动命令。
|
||||
- 远端日志使用异步队列,队列满时允许丢弃远端事件,优先保护抢购链路。
|
||||
- 远端控制当前定位于监控、日志汇总、结果查看和应急停止。
|
||||
|
||||
## 2. 总体架构
|
||||
|
||||
```text
|
||||
抢购电脑
|
||||
实例 1 ─┐
|
||||
实例 2 ─┼─ 每个实例独立异步上报
|
||||
实例 N ─┘
|
||||
│
|
||||
│ WebSocket 主动外连 + HTTP 自动注册
|
||||
↓
|
||||
远端控制中心 douyu-control
|
||||
├─ 机器/实例在线状态
|
||||
├─ 结构化实时日志
|
||||
├─ 抢购运行摘要
|
||||
├─ 命令下发与回执
|
||||
├─ CSV / JSON 导出
|
||||
└─ Web 管理页面
|
||||
↑
|
||||
│ 浏览器访问
|
||||
│
|
||||
管理电脑 / 手机
|
||||
```
|
||||
|
||||
一台机器可以运行任意数量的实例。服务端只按 `machineId` 聚合,不假定固定数量、实例编号连续或每台机器必须启动几个实例。
|
||||
|
||||
## 3. 主要代码
|
||||
|
||||
| 路径 | 职责 |
|
||||
|---|---|
|
||||
| `internal/remote/protocol.go` | 实例状态、日志、命令和 WebSocket 消息结构 |
|
||||
| `internal/remote/agent.go` | 桌面实例连接、重连、心跳、命令执行 |
|
||||
| `internal/remote/credentials.go` | 自动注册和实例凭据保存 |
|
||||
| `internal/remote/spool.go` | 非阻塞日志落盘、断线续传偏移 |
|
||||
| `internal/remote/machine.go` | 本机稳定机器 ID |
|
||||
| `internal/remote/server.go` | HTTP API、WebSocket Agent 接入、鉴权 |
|
||||
| `internal/remote/token_store.go` | 服务端实例令牌签发和持久化 |
|
||||
| `internal/remote/hub.go` | 机器状态、运行记录、日志、导出 |
|
||||
| `internal/remote/web/index.html` | 远端 Web 控制台 |
|
||||
| `internal/app/app_remote.go` | 桌面 App 与远端 Agent 的连接 |
|
||||
| `internal/logger/logger.go` | 本地日志到远端观察器的非阻塞分发 |
|
||||
| `cmd/douyu-control/main.go` | 控制中心启动入口 |
|
||||
| `frontend/src/components/layout/RightConsole.vue` | 主界面远端状态入口 |
|
||||
| `frontend/src/components/modal/SettingsModal.vue` | 桌面端远端设置 |
|
||||
|
||||
## 4. 身份与聚合
|
||||
|
||||
### 机器 ID
|
||||
|
||||
每个抢购机器生成一次稳定的随机 `machineId`,同一台电脑上的所有实例共享。
|
||||
|
||||
默认位置:
|
||||
|
||||
```text
|
||||
<机器数据根目录>/remote/machine_id
|
||||
```
|
||||
|
||||
控制台按 `machineId` 聚合机器,再展示这台机器下所有在线或最近连接的实例。
|
||||
|
||||
### 实例 ID
|
||||
|
||||
实例 ID 使用软件当前的实例名称,例如:
|
||||
|
||||
```text
|
||||
默认实例
|
||||
实例 2
|
||||
实例 3
|
||||
临时实例
|
||||
```
|
||||
|
||||
服务端不要求实例编号连续,也不要求每台机器实例数量一致。
|
||||
|
||||
## 5. 自动注册与令牌
|
||||
|
||||
实例令牌全自动获取,不需要人工复制。首次注册需要控制中心注册令牌,桌面端填写正确的控制中心地址和注册令牌即可。
|
||||
|
||||
### 首次注册
|
||||
|
||||
1. 桌面实例启用远端控制,填写控制中心地址和注册令牌。
|
||||
2. Agent 携带 `X-Enroll-Token` 请求 `POST /api/enroll`。
|
||||
3. 控制中心为该 `machineId + instanceId` 签发独立令牌。
|
||||
4. 令牌保存在本机实例数据目录。
|
||||
5. Agent 使用令牌连接 `/ws/agent`。
|
||||
6. 后续重连直接复用本地令牌。
|
||||
|
||||
### 自动注册窗口
|
||||
|
||||
如果服务端没有配置注册口令,则控制中心启动后开放一个注册窗口。
|
||||
|
||||
- 默认窗口:10 分钟。
|
||||
- 可通过 `-enroll-window` 或 `DOUYU_CONTROL_ENROLL_WINDOW` 修改。
|
||||
- 窗口关闭后不接受新的实例注册。
|
||||
- 已注册实例不受窗口关闭影响。
|
||||
- 已有令牌继续有效。
|
||||
|
||||
公网部署必须配置 `-enroll-token` 或 `DOUYU_CONTROL_ENROLL_TOKEN`,避免开放自动注册窗口。桌面端“注册令牌”填写同一个值。
|
||||
|
||||
注册令牌只用于首次换取实例令牌,不会作为 WebSocket 连接令牌持续使用。
|
||||
|
||||
### 令牌文件
|
||||
|
||||
服务端:
|
||||
|
||||
```text
|
||||
<控制中心数据目录>/agent_tokens.json
|
||||
```
|
||||
|
||||
桌面实例:
|
||||
|
||||
```text
|
||||
<机器数据根目录>/remote/instances/<实例数据目录名>.json
|
||||
```
|
||||
|
||||
### 鉴权
|
||||
|
||||
- 管理接口必须携带管理令牌。
|
||||
- Agent WebSocket 必须携带由服务端签发的实例令牌。
|
||||
- 无有效令牌访问受保护接口返回 `401`。
|
||||
- 实例令牌与 `machineId + instanceId` 不匹配时,WebSocket 会被关闭。
|
||||
|
||||
旧版共享 `-agent-token` 仍保留兼容,但不是默认使用方式。
|
||||
|
||||
## 6. 桌面端配置
|
||||
|
||||
设置路径:
|
||||
|
||||
```text
|
||||
设置 -> 远端控制
|
||||
```
|
||||
|
||||
字段:
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| 启用远端上报 | 开启或关闭当前实例的远端功能 |
|
||||
| 控制中心地址 | 例如 `https://control.example.com` |
|
||||
| 注册令牌 | 与控制中心的 `DOUYU_CONTROL_ENROLL_TOKEN` 相同 |
|
||||
| 机器显示名称 | 留空时使用主机名 |
|
||||
|
||||
实例令牌不需要填写,也不会显示在设置中。旧版 `remoteToken` 仅作为兼容字段保留。
|
||||
|
||||
控制中心地址必须是根地址,例如 `https://control.example.com`。不要填写 `/#admin=...`、查询参数或子路径。
|
||||
|
||||
主界面顶栏会显示远端状态:
|
||||
|
||||
- `远端 · 未启用`
|
||||
- `远端 · 连接中`
|
||||
- `远端 · 已连接`
|
||||
|
||||
点击状态按钮会打开设置并定位到远端区域。
|
||||
|
||||
远端配置也可以写入共享配置 JSON 的 `remote` 字段,其中 `enrollmentToken` 用于给新实例统一注册。共享文件可能包含注册令牌,应当限制文件权限。
|
||||
|
||||
## 7. 启动控制中心
|
||||
|
||||
### Docker Compose
|
||||
|
||||
部署文件位于:
|
||||
|
||||
```text
|
||||
deploy/control-center/
|
||||
```
|
||||
|
||||
该目录包含 Dockerfile、Compose、环境变量示例、Caddy 示例和部署说明。继续复用宿主机现有 Caddy,Compose 只暴露回环地址:
|
||||
|
||||
```text
|
||||
127.0.0.1:18080
|
||||
```
|
||||
|
||||
完整步骤见:
|
||||
|
||||
```text
|
||||
deploy/control-center/README.md
|
||||
```
|
||||
|
||||
### 单二进制
|
||||
|
||||
构建:
|
||||
|
||||
```bash
|
||||
./build.sh control
|
||||
```
|
||||
|
||||
本地启动:
|
||||
|
||||
```bash
|
||||
./build/bin/douyu-control \
|
||||
-addr :18080 \
|
||||
-data '/Users/yml/Library/Application Support/douyu-go-control'
|
||||
```
|
||||
|
||||
不指定管理令牌时,程序会随机生成,并打印可自动登录的 Web 地址:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:18080/#admin=<管理令牌>
|
||||
```
|
||||
|
||||
`#admin` 是浏览器本地片段,不会发送给服务器。Web 页面读取后保存到浏览器本地,并立即从地址栏移除。
|
||||
|
||||
局域网其他电脑访问时使用本机局域网 IP,例如:
|
||||
|
||||
```text
|
||||
http://192.168.10.6:18080/#admin=<管理令牌>
|
||||
```
|
||||
|
||||
桌面实例填写不带 `#admin` 的地址:
|
||||
|
||||
```text
|
||||
http://192.168.10.6:18080
|
||||
```
|
||||
|
||||
公网部署时改为:
|
||||
|
||||
```text
|
||||
https://control.example.com
|
||||
```
|
||||
|
||||
## 8. 启动参数与环境变量
|
||||
|
||||
| 参数 | 环境变量 | 默认值 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `-addr` | `DOUYU_CONTROL_ADDR` | `:18080` | HTTP 监听地址 |
|
||||
| `-data` | `DOUYU_CONTROL_DATA` | `remote-data` | 控制中心数据目录 |
|
||||
| `-operator-token` | `DOUYU_CONTROL_OPERATOR_TOKEN` | 随机生成 | Web 管理令牌 |
|
||||
| `-enroll-token` | `DOUYU_CONTROL_ENROLL_TOKEN` | 空 | 新实例注册口令 |
|
||||
| `-enroll-window` | `DOUYU_CONTROL_ENROLL_WINDOW` | `10m` | 无注册口令时的自动注册窗口 |
|
||||
| `-agent-token` | `DOUYU_CONTROL_AGENT_TOKEN` | 空 | 兼容旧版共享实例令牌 |
|
||||
|
||||
公网使用时必须在前面配置 HTTPS 反向代理。
|
||||
|
||||
## 9. Web 控制台功能
|
||||
|
||||
### 机器与实例
|
||||
|
||||
- 按机器动态聚合并展示任意数量实例。
|
||||
- 显示在线状态、运行状态、账号数和当前结果数量。
|
||||
- 点击“结果”展开当前账号结果。
|
||||
- 点击“日志”只看该实例日志。
|
||||
- 点击“刷新”立即请求实例状态。
|
||||
- 点击“停止”请求本地实例停止抢购。
|
||||
- 点击“取消定时”请求本地实例取消尚未触发的定时任务。
|
||||
|
||||
### 最近运行
|
||||
|
||||
- 显示最近运行记录:开始时间、机器、实例、运行状态和结果数量。
|
||||
- 点击某条运行记录,只看该 `runId` 的日志。
|
||||
|
||||
### 实时日志
|
||||
|
||||
日志字段:
|
||||
|
||||
```text
|
||||
机器 ID
|
||||
机器名称
|
||||
实例 ID
|
||||
实例名称
|
||||
运行 ID
|
||||
本地时间
|
||||
类别
|
||||
等级
|
||||
账号
|
||||
日志正文
|
||||
```
|
||||
|
||||
日志支持:
|
||||
|
||||
- 按实例筛选。
|
||||
- 按运行筛选。
|
||||
- 按实例名、账号或正文过滤。
|
||||
- 恢复全部日志。
|
||||
- 清空当前浏览器显示,不删除服务端数据。
|
||||
|
||||
## 10. 导出
|
||||
|
||||
Web 控制台提供:
|
||||
|
||||
- `导出 CSV`
|
||||
- `导出 JSON`
|
||||
|
||||
导出会应用当前选择条件:
|
||||
|
||||
- 当前实例。
|
||||
- 当前运行。
|
||||
- 当前文本过滤条件。
|
||||
- 没有选择实例时导出全部机器日志。
|
||||
|
||||
CSV 使用 UTF-8 BOM,兼容 Excel 中文。
|
||||
|
||||
CSV 列:
|
||||
|
||||
```text
|
||||
seq
|
||||
time
|
||||
machine_id
|
||||
machine_name
|
||||
instance_id
|
||||
instance_name
|
||||
run_id
|
||||
category
|
||||
level
|
||||
account
|
||||
message
|
||||
```
|
||||
|
||||
接口:
|
||||
|
||||
```text
|
||||
GET /api/export?format=csv
|
||||
GET /api/export?format=json
|
||||
```
|
||||
|
||||
可选参数:
|
||||
|
||||
```text
|
||||
machineId
|
||||
instanceId
|
||||
runId
|
||||
q
|
||||
from RFC3339
|
||||
to RFC3339
|
||||
```
|
||||
|
||||
## 11. 数据保存位置
|
||||
|
||||
### 控制中心
|
||||
|
||||
```text
|
||||
<控制中心数据目录>/
|
||||
events.ndjson # 所有结构化日志
|
||||
runs.ndjson # 运行摘要历史
|
||||
agent_tokens.json # 实例独立令牌
|
||||
```
|
||||
|
||||
`events.ndjson` 是日志统计和导出的权威数据源。
|
||||
|
||||
### 抢购实例
|
||||
|
||||
```text
|
||||
<实例数据目录>/remote/
|
||||
events.ndjson # 待上传事件
|
||||
events.offset # 已上传偏移
|
||||
```
|
||||
|
||||
本机机器和凭据:
|
||||
|
||||
```text
|
||||
<机器数据根目录>/remote/machine_id
|
||||
<机器数据根目录>/remote/instances/<实例>.json
|
||||
```
|
||||
|
||||
软件原本的人类可读日志仍保存在各实例的 `LogDir`,远端功能不会删除或替换本地日志。
|
||||
|
||||
## 12. 异步与离线行为
|
||||
|
||||
- 日志先进入内存队列,再由独立 goroutine 追加到本地远端事件文件。
|
||||
- 网络发送与抢购请求完全解耦。
|
||||
- 队列满时丢弃远端事件,并增加 `DroppedEvents` 计数。
|
||||
- Agent 断线后继续写本地事件文件。
|
||||
- 重连后从 `events.offset` 继续上传。
|
||||
- 心跳每 5 秒发送一次状态。
|
||||
- 连接失败使用指数退避,最长 30 秒。
|
||||
- 服务端重启不会清空已注册实例令牌。
|
||||
|
||||
## 13. 命令
|
||||
|
||||
当前支持:
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `ping` | 连通性检查 |
|
||||
| `status` | 立即刷新实例状态 |
|
||||
| `stop` | 请求停止当前抢购 |
|
||||
| `cancel_schedule` | 取消尚未触发的定时任务 |
|
||||
|
||||
暂不支持:
|
||||
|
||||
- 远端启动抢购。
|
||||
- 远端创建定时任务。
|
||||
- 远端修改账号或 Cookie。
|
||||
- 任意 Shell 命令。
|
||||
|
||||
这是刻意的安全边界。抢购启动和时序必须由本地实例负责。
|
||||
|
||||
## 14. 安全要求
|
||||
|
||||
- 远端日志不能包含 Cookie、CSRF、代理密码、白名单签名密钥或 Trace 原始请求正文。
|
||||
- Trace 文件不会自动上传。
|
||||
- 公网部署必须使用 HTTPS/WSS。
|
||||
- 公网部署必须设置注册令牌,不允许长期开放自动注册窗口。
|
||||
- 桌面端注册令牌只用于 `POST /api/enroll`,注册成功后连接使用服务端签发的独立实例令牌。
|
||||
- 管理令牌和实例令牌必须使用高强度随机值。
|
||||
- 管理操作应保留命令审计。
|
||||
- 日志中包含斗鱼账号名称,导出文件应按敏感数据处理。
|
||||
- 不应允许远端修改账号凭据或执行任意命令。
|
||||
|
||||
## 15. 当前限制
|
||||
|
||||
- `/Users/yml/日志/斗鱼/11.21` 这类历史文本日志不会自动导入。
|
||||
- 只有启用远端之后产生的结构化日志会自动收集。
|
||||
- 历史文本日志需要单独实现导入/回填工具。
|
||||
- 服务端当前使用 NDJSON 持久化,不是数据库。
|
||||
- 尚未实现日志按天自动清理、全文检索、用户权限分级和集群部署。
|
||||
- 远端控制台依赖一个常驻的 `douyu-control` 服务进程,但管理端不需要安装 Windows/macOS 客户端。
|
||||
|
||||
## 16. 验证
|
||||
|
||||
远端相关修改至少运行:
|
||||
|
||||
```bash
|
||||
go test ./...
|
||||
go test -race ./internal/remote
|
||||
cd frontend && npm run type-check
|
||||
docker compose -f deploy/control-center/compose.yaml config
|
||||
./build.sh control
|
||||
./build.sh build
|
||||
```
|
||||
|
||||
手工检查:
|
||||
|
||||
```text
|
||||
GET /api/health
|
||||
GET /api/dashboard 无令牌返回 401
|
||||
POST /api/enroll 注册窗口内可签发令牌
|
||||
GET /api/export?format=csv 能下载带 BOM 的日志
|
||||
GET /api/export?format=json 能下载结构化日志
|
||||
```
|
||||
|
||||
## 17. 变更记录
|
||||
|
||||
| 日期 | 变更 |
|
||||
|---|---|
|
||||
| 2026-11-21 | 建立远端控制、自动注册、动态机器聚合、实时日志、运行记录、主界面状态入口、CSV/JSON 导出 |
|
||||
| 2026-11-21 | 实例快照增加结构化代理状态,Web 控制台可查看代理组、出口和账号分组 |
|
||||
| 2026-11-21 | 增加独立注册令牌配置和 `deploy/control-center` Docker/Caddy 部署目录 |
|
||||
|
||||
## 18. 代理白名单协同规划
|
||||
|
||||
远端控制中心后续统一管理代理白名单,但不得成为本地抢购的单点依赖。
|
||||
|
||||
建议能力:
|
||||
|
||||
- 按 `machineId` 收集每台电脑的公网 IP。
|
||||
- 为每台机器维护一个白名单状态,而不是每个实例一个。
|
||||
- 使用全局串行队列下发幂等的 `ensure_whitelist` 命令。
|
||||
- 命令由机器本地 Agent 使用本机凭据执行并回报结果。
|
||||
- 控制中心等待回执后再推进下一台机器。
|
||||
- 遵守平台频率限制,例如每秒最多一次。
|
||||
- 展示 `pending`、`ready`、`failed`、`expired` 和最近检查时间。
|
||||
- 在抢购前更早完成,例如 `T-10min` 或 `T-5min`。
|
||||
- 将白名单状态推送给该机器的所有实例。
|
||||
|
||||
边界要求:
|
||||
|
||||
- 本地实例仍需缓存白名单状态。
|
||||
- 远端不可用时,本地必须能继续执行幂等兜底。
|
||||
- 白名单管理不能依赖 `T-0s` 的远端实时命令。
|
||||
- 品赞登录密码和签名密钥保存在抢购电脑本地,不集中上传控制中心,不得进入日志或远端事件。
|
||||
- 代理提取结果必须使用 JSON;TXT 会丢失用户名密码。
|
||||
|
||||
当前状态:方向已确认,尚未实现。
|
||||
|
||||
## 19. 实例代理状态展示
|
||||
|
||||
远端控制台中的每个实例必须直接显示代理状态和账号分组,而不是要求用户查看日志推导。
|
||||
|
||||
实例摘要建议显示:
|
||||
|
||||
```text
|
||||
活动代理 4 · 备用 1/1 · 直连回退 0
|
||||
```
|
||||
|
||||
实例展开后显示:
|
||||
|
||||
- 代理组编号。
|
||||
- 每组账号数量。
|
||||
- 脱敏后的代理出口、地区和 RTT。
|
||||
- 当前状态:使用中、备用、失败、直连。
|
||||
- 最近切换次数和最后错误。
|
||||
- 每个账号属于哪个组。
|
||||
- 白名单状态。
|
||||
|
||||
Agent Snapshot 已增加结构化 `proxyStatus` 字段,日志只作为审计时间线,不能作为界面状态来源。
|
||||
|
||||
当前状态:已实现。
|
||||
|
||||
- 实例摘要显示活动代理、备用代理和直连数量。
|
||||
- “代理”按钮展开组号、账号数、状态、脱敏出口、地区、RTT、切换次数和最近错误。
|
||||
- 状态区分准备中、就绪、降级、失败和直连回退。
|
||||
- 代理快照不包含代理用户名、密码或白名单签名密钥。
|
||||
- 桌面端和远端使用同一份 `ProxyStatusView`,避免两边口径不一致。
|
||||
@@ -6,6 +6,7 @@ import { useProducts } from '@/composables/useProducts'
|
||||
import type { Product } from '@/composables/useProducts'
|
||||
import { useActivity } from '@/composables/useActivity'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { useProxyStatus } from '@/composables/useProxyStatus'
|
||||
import { formatExchangeTime, formatShortExchangeTime } from '@/utils/formatTime'
|
||||
import {
|
||||
ExportLatestXiaodianReport,
|
||||
@@ -35,6 +36,7 @@ const {
|
||||
const { products, selectedProductId, selectedProductName, selectProduct, clearSelection } = useProducts()
|
||||
const { currentActivity } = useActivity()
|
||||
const { showToast } = useToast()
|
||||
const { getAccountProxy } = useProxyStatus()
|
||||
const isXiaodian = computed(() => currentActivity.value?.id === 'xiaodian')
|
||||
const productFilterMap = ref<Record<string, string>>({})
|
||||
const openProductAccount = ref<string | null>(null)
|
||||
@@ -411,6 +413,7 @@ const closeExchangeRecords = () => {
|
||||
<th v-if="isXiaodian">扭蛋碎片</th>
|
||||
<th v-if="isXiaodian">角色信息</th>
|
||||
<th class="exchange-record-col">兑换记录</th>
|
||||
<th class="proxy-col">代理</th>
|
||||
<th class="status-col">状态</th>
|
||||
<th>最后结果</th>
|
||||
<th class="account-action-col">操作</th>
|
||||
@@ -418,7 +421,7 @@ const closeExchangeRecords = () => {
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="accounts.length === 0">
|
||||
<td :colspan="isXiaodian ? 12 : 10" class="empty-state">暂无账号,请加载账号</td>
|
||||
<td :colspan="isXiaodian ? 13 : 11" class="empty-state">暂无账号,请加载账号</td>
|
||||
</tr>
|
||||
<template v-else>
|
||||
<tr
|
||||
@@ -550,6 +553,17 @@ const closeExchangeRecords = () => {
|
||||
>{{ recordSummary(account.name) }}</div>
|
||||
<button class="btn btn-compact btn-records" @click.stop="openExchangeRecords(account.name)">记录</button>
|
||||
</td>
|
||||
<td class="proxy-cell">
|
||||
<span
|
||||
v-if="getAccountProxy(account.name)"
|
||||
class="proxy-badge"
|
||||
:class="getAccountProxy(account.name)?.transport"
|
||||
:title="getAccountProxy(account.name)?.proxy || ''"
|
||||
>
|
||||
{{ getAccountProxy(account.name)?.groupLabel }}
|
||||
</span>
|
||||
<span v-else class="account-sub">-</span>
|
||||
</td>
|
||||
<td class="status-td">
|
||||
<span
|
||||
class="status-badge"
|
||||
@@ -828,6 +842,40 @@ tbody tr:hover {
|
||||
width: 96px;
|
||||
}
|
||||
|
||||
.proxy-col,
|
||||
.proxy-cell {
|
||||
width: 76px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.proxy-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: var(--surface-2);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.proxy-badge.proxy {
|
||||
color: var(--success);
|
||||
border-color: var(--success);
|
||||
background: var(--success-soft);
|
||||
}
|
||||
|
||||
.proxy-badge.direct {
|
||||
color: var(--danger);
|
||||
border-color: var(--danger);
|
||||
background: var(--danger-soft);
|
||||
}
|
||||
|
||||
.proxy-badge.unassigned {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.account-action-col,
|
||||
.account-action-cell {
|
||||
width: 92px;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useProxyStatus } from '@/composables/useProxyStatus'
|
||||
|
||||
const { proxyStatus } = useProxyStatus()
|
||||
|
||||
const stateLabel = computed(() => {
|
||||
const status = proxyStatus.value
|
||||
if (!status.enabled) return '本地直连'
|
||||
if (status.state === 'ready') return status.required ? '严格代理已就绪' : '代理已就绪'
|
||||
if (status.state === 'degraded') return '代理降级运行'
|
||||
if (status.state === 'direct_fallback') return '代理故障回退直连'
|
||||
if (status.state === 'failed') return status.required ? '严格代理准备失败' : '代理准备失败'
|
||||
if (status.state === 'preparing') return '代理准备中'
|
||||
if (status.state === 'stale') return '代理配置已变更'
|
||||
return status.required ? '严格代理未准备' : '代理未准备'
|
||||
})
|
||||
|
||||
const stateClass = computed(() => ({
|
||||
warning: ['direct_fallback', 'failed', 'degraded', 'stale'].includes(proxyStatus.value.state),
|
||||
active: proxyStatus.value.state === 'ready',
|
||||
idle: !proxyStatus.value.enabled
|
||||
}))
|
||||
|
||||
const groups = computed(() => (proxyStatus.value.groups || []).filter(group => group.role === 'active'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="proxy-strip">
|
||||
<div class="proxy-title">
|
||||
<span class="state-dot" :class="stateClass"></span>
|
||||
<strong>{{ stateLabel }}</strong>
|
||||
<span v-if="proxyStatus.enabled" class="sub">
|
||||
活动 {{ proxyStatus.activeCount }} · 备用 {{ proxyStatus.standbyCount }}/{{ proxyStatus.standbyTarget }} · 直连 {{ proxyStatus.directCount }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="groups.length" class="group-list">
|
||||
<span
|
||||
v-for="group in groups"
|
||||
:key="group.groupIndex"
|
||||
class="group-chip"
|
||||
:class="group.state"
|
||||
:title="`${group.proxy || '直连'}${group.region ? ' · ' + group.region : ''}${group.rttMs ? ' · ' + group.rttMs + 'ms' : ''}${group.lastError ? ' · ' + group.lastError : ''}`"
|
||||
>
|
||||
G{{ group.groupIndex }}
|
||||
<span>{{ group.state === 'direct' ? '直连' : group.state === 'failed' ? '失败' : `${group.accountCount}号` }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="proxyStatus.lastError" class="proxy-error" :title="proxyStatus.lastError">{{ proxyStatus.lastError }}</span>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.proxy-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-height: 38px;
|
||||
padding: 7px 20px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--surface);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.proxy-title, .group-list {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.proxy-title {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.sub, .proxy-error {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.proxy-error {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.state-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.state-dot.active { background: var(--success); }
|
||||
.state-dot.warning { background: var(--warning); }
|
||||
.state-dot.idle { background: var(--muted); }
|
||||
|
||||
.group-list {
|
||||
overflow: auto hidden;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.group-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 999px;
|
||||
background: var(--surface-2);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-chip.active {
|
||||
color: var(--success);
|
||||
border-color: var(--success);
|
||||
background: var(--success-soft);
|
||||
}
|
||||
|
||||
.group-chip.direct, .group-chip.failed {
|
||||
color: var(--danger);
|
||||
border-color: var(--danger);
|
||||
background: var(--danger-soft);
|
||||
}
|
||||
</style>
|
||||
@@ -5,12 +5,14 @@ import { useScheduler } from '@/composables/useScheduler'
|
||||
import { useSettings } from '@/composables/useSettings'
|
||||
import StatusGrid from '@/components/console/StatusGrid.vue'
|
||||
import ControlStrip from '@/components/console/ControlStrip.vue'
|
||||
import ProxyGroupPanel from '@/components/console/ProxyGroupPanel.vue'
|
||||
import AccountTable from '@/components/account/AccountTable.vue'
|
||||
import LogPanel from '@/components/log/LogPanel.vue'
|
||||
import SettingsModal from '@/components/modal/SettingsModal.vue'
|
||||
import CKManager from '@/components/ck/CKManager.vue'
|
||||
import ExchangeRecords from '@/components/exchange/ExchangeRecords.vue'
|
||||
import { GetRemoteStatus } from '@wails/go/app/App'
|
||||
import { useProxyStatus } from '@/composables/useProxyStatus'
|
||||
|
||||
defineProps<{
|
||||
serverTime: string
|
||||
@@ -19,6 +21,7 @@ defineProps<{
|
||||
const { theme, toggleTheme } = useTheme()
|
||||
const { runState, countdownSeconds, formatRemain } = useScheduler()
|
||||
const { settings, loadSettings } = useSettings()
|
||||
const { loadProxyStatus } = useProxyStatus()
|
||||
|
||||
const settingsModalRef = ref<InstanceType<typeof SettingsModal> | null>(null)
|
||||
const currentPage = ref<'console' | 'ck' | 'exchange'>('console')
|
||||
@@ -28,6 +31,7 @@ const remoteStatus = ref<{
|
||||
message?: string
|
||||
}>({ enabled: false, connected: false })
|
||||
let remoteStatusTimer: number | null = null
|
||||
let proxyStatusTimer: number | null = null
|
||||
|
||||
const proxyAutoFetchReady = computed(() => (
|
||||
settings.value.proxyEnabled
|
||||
@@ -44,7 +48,7 @@ const proxyNeedsApi = computed(() => (
|
||||
const proxySummary = computed(() => {
|
||||
if (!settings.value.proxyEnabled) return '代理未启用'
|
||||
const size = settings.value.accountsPerProxy || 5
|
||||
const spare = settings.value.proxySparePercent || 25
|
||||
const spare = settings.value.proxySparePercent || 50
|
||||
if (!settings.value.autoFetchProxyOnSchedule) return `代理 · ${size}号/组 · 备用${spare}%`
|
||||
if (!settings.value.proxyApi.trim()) return `代理 · ${size}号/组 · 缺少 API`
|
||||
return `代理 · ${size}号/组 · 备用${spare}% · 预取`
|
||||
@@ -53,7 +57,7 @@ const proxySummary = computed(() => {
|
||||
const proxyTitle = computed(() => {
|
||||
if (!settings.value.proxyEnabled) return '代理尚未启用,点击配置'
|
||||
if (proxyNeedsApi.value) return '已开启定时预取,但缺少代理提取 API;点击配置'
|
||||
if (proxyAutoFetchReady.value) return '定时抢购触发前 30 秒自动提取并校验代理;点击查看设置'
|
||||
if (proxyAutoFetchReady.value) return '定时抢购触发前 2 分钟自动提取并校验代理;点击查看设置'
|
||||
return '代理已启用,点击打开代理设置'
|
||||
})
|
||||
|
||||
@@ -86,11 +90,14 @@ const refreshRemoteStatus = async () => {
|
||||
onMounted(async () => {
|
||||
await loadSettings()
|
||||
await refreshRemoteStatus()
|
||||
await loadProxyStatus()
|
||||
remoteStatusTimer = window.setInterval(refreshRemoteStatus, 3000)
|
||||
proxyStatusTimer = window.setInterval(loadProxyStatus, 2000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (remoteStatusTimer) clearInterval(remoteStatusTimer)
|
||||
if (proxyStatusTimer) clearInterval(proxyStatusTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -141,6 +148,7 @@ onUnmounted(() => {
|
||||
<template v-if="currentPage === 'console'">
|
||||
<StatusGrid :server-time="serverTime" />
|
||||
<ControlStrip />
|
||||
<ProxyGroupPanel />
|
||||
<section class="console-workspace">
|
||||
<AccountTable />
|
||||
</section>
|
||||
|
||||
@@ -30,19 +30,21 @@ const formData = ref({
|
||||
seckillMode: 1,
|
||||
xiaodianPageSize: 200,
|
||||
proxyEnabled: false,
|
||||
proxyRequired: true,
|
||||
proxyUrl: '',
|
||||
proxyApi: '',
|
||||
sharedProxyConfigFile: '',
|
||||
proxyExpiresAt: 0,
|
||||
autoFetchProxyOnSchedule: false,
|
||||
accountsPerProxy: 5,
|
||||
proxySparePercent: 25,
|
||||
proxySparePercent: 50,
|
||||
proxyAutoWhitelist: false,
|
||||
proxyWhitelistReplace: true,
|
||||
proxyWhitelistPassword: '',
|
||||
proxyWhitelistSignKey: '',
|
||||
remoteEnabled: false,
|
||||
remoteUrl: '',
|
||||
remoteEnrollmentToken: '',
|
||||
remoteToken: '',
|
||||
remoteMachineName: ''
|
||||
})
|
||||
@@ -61,10 +63,10 @@ const proxyOverviewTitle = computed(() => (
|
||||
const proxyOverviewDetail = computed(() => {
|
||||
if (!formData.value.proxyEnabled) return '启用后可配置账号分组、提取 API 和自动预取'
|
||||
const size = formData.value.accountsPerProxy || 5
|
||||
const spare = formData.value.proxySparePercent || 25
|
||||
const spare = formData.value.proxySparePercent || 50
|
||||
if (!formData.value.autoFetchProxyOnSchedule) return `当前每 ${size} 个账号一个代理,备用 ${spare}%`
|
||||
if (!formData.value.proxyApi.trim()) return '已开启自动预取,但尚未填写代理提取 API'
|
||||
return `每 ${size} 个账号一组,备用 ${spare}%;定时抢购触发前 30 秒自动预取`
|
||||
return `每 ${size} 个账号一组,备用 ${spare}%;定时抢购触发前 2 分钟自动预取`
|
||||
})
|
||||
|
||||
const proxyAutoFetchReady = computed(() => (
|
||||
@@ -324,6 +326,19 @@ defineExpose({ open, close })
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<div class="toggle-row">
|
||||
<div>
|
||||
<span class="toggle-label">严格代理模式</span>
|
||||
<div class="form-hint">代理未就绪时中止抢购,运行中也不自动回退直连</div>
|
||||
</div>
|
||||
<label class="toggle">
|
||||
<input v-model="formData.proxyRequired" type="checkbox">
|
||||
<span class="toggle-slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="shared-config-box">
|
||||
<div class="shared-config-title">共享代理配置</div>
|
||||
<div class="shared-config-path">
|
||||
@@ -341,7 +356,7 @@ defineExpose({ open, close })
|
||||
<button type="button" class="btn btn-ghost btn-sm" @click="handleSaveSharedProxyConfig">保存到共享文件</button>
|
||||
</div>
|
||||
<div class="form-hint">
|
||||
共享文件包含代理提取 API、分组、备用比例、白名单和远端控制设置,不包含账号、CK、当前代理 IP 或过期时间。文件中可能包含密码、签名密钥和远端令牌,请妥善保管。
|
||||
共享文件包含代理提取 API、分组、备用比例、白名单和远端控制设置,不包含账号、CK、当前代理 IP 或过期时间。文件中可能包含密码、签名密钥和注册令牌,请妥善保管。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -367,12 +382,12 @@ defineExpose({ open, close })
|
||||
v-model.number="formData.proxySparePercent"
|
||||
class="form-input"
|
||||
type="number"
|
||||
min="1"
|
||||
min="50"
|
||||
max="100"
|
||||
step="1"
|
||||
>
|
||||
<div class="form-hint">
|
||||
默认 25%,至少备用 1 个;6 个活动组会额外提取 2 个备用代理。
|
||||
最低 50%,默认 50%;4 个活动组会额外提取 2 个备用代理。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -435,10 +450,10 @@ defineExpose({ open, close })
|
||||
<div class="form-group">
|
||||
<label class="checkbox-row">
|
||||
<input v-model="formData.autoFetchProxyOnSchedule" type="checkbox">
|
||||
<span class="checkbox-text">定时抢购触发前 30 秒自动预取并校验代理</span>
|
||||
<span class="checkbox-text">定时抢购触发前 2 分钟自动预取并校验代理</span>
|
||||
</label>
|
||||
<div class="form-hint">
|
||||
仅对定时抢购生效。按“每组账号数”提取对应数量并校验;立即抢购会在开始前同步准备代理。建议使用 10 分钟以上时长,覆盖抢购与最长 180 秒支付。
|
||||
按“每组账号数”提取对应数量并校验;严格代理模式下定时抢购始终提前 2 分钟准备。立即抢购会在开始前同步准备代理。建议使用 10 分钟以上时长,覆盖抢购与最长 180 秒支付。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -589,11 +604,22 @@ defineExpose({ open, close })
|
||||
<input
|
||||
v-model="formData.remoteUrl"
|
||||
class="form-input"
|
||||
type="text"
|
||||
type="url"
|
||||
placeholder="https://control.example.com 或 http://127.0.0.1:18080"
|
||||
>
|
||||
<div class="form-hint">只填写控制中心根地址,不要带 /#admin= 后面的管理令牌。</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label class="form-label">注册令牌</label>
|
||||
<input
|
||||
v-model="formData.remoteEnrollmentToken"
|
||||
class="form-input"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
placeholder="填写控制中心的 DOUYU_CONTROL_ENROLL_TOKEN"
|
||||
>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="form-label">机器显示名称</label>
|
||||
<input
|
||||
@@ -605,7 +631,7 @@ defineExpose({ open, close })
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-hint">
|
||||
首次连接会在控制中心注册窗口内自动领取独立实例令牌并保存在本机,无需手工配置。
|
||||
首次连接使用注册令牌领取独立实例令牌并保存在本机,后续不需要再次填写。注册令牌只用于注册,不会作为实例连接令牌使用。
|
||||
Cookie、CSRF、代理密码、签名密钥和 Trace 内容不会上传。远端只接收结构化日志、运行摘要和控制命令。
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { GetProxyStatus } from '@wails/go/app/App'
|
||||
|
||||
export interface ProxyGroupStatus {
|
||||
groupIndex: number
|
||||
role: string
|
||||
state: string
|
||||
accountCount: number
|
||||
accounts?: string[]
|
||||
proxy?: string
|
||||
region?: string
|
||||
rttMs?: number
|
||||
switchCount: number
|
||||
lastError?: string
|
||||
}
|
||||
|
||||
export interface AccountProxyView {
|
||||
accountName: string
|
||||
groupIndex?: number
|
||||
groupLabel: string
|
||||
transport: string
|
||||
proxy?: string
|
||||
}
|
||||
|
||||
export interface ProxyStatus {
|
||||
enabled: boolean
|
||||
required: boolean
|
||||
state: string
|
||||
activeCount: number
|
||||
standbyCount: number
|
||||
standbyTarget: number
|
||||
directCount: number
|
||||
lastError?: string
|
||||
updatedAt: string
|
||||
groups: ProxyGroupStatus[]
|
||||
accounts: AccountProxyView[]
|
||||
}
|
||||
|
||||
const proxyStatus = ref<ProxyStatus>({
|
||||
enabled: false,
|
||||
required: false,
|
||||
state: 'not-loaded',
|
||||
activeCount: 0,
|
||||
standbyCount: 0,
|
||||
standbyTarget: 0,
|
||||
directCount: 0,
|
||||
updatedAt: '',
|
||||
groups: [],
|
||||
accounts: []
|
||||
})
|
||||
|
||||
const accountProxyMap = computed(() => {
|
||||
const out: Record<string, AccountProxyView> = {}
|
||||
for (const account of proxyStatus.value.accounts || []) {
|
||||
out[account.accountName] = account
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
export function useProxyStatus() {
|
||||
const loadProxyStatus = async () => {
|
||||
try {
|
||||
proxyStatus.value = await GetProxyStatus()
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const getAccountProxy = (accountName: string) => accountProxyMap.value[accountName]
|
||||
|
||||
return {
|
||||
proxyStatus,
|
||||
loadProxyStatus,
|
||||
getAccountProxy
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export interface Settings {
|
||||
seckillMode: number // 0=标准, 1=激进
|
||||
xiaodianPageSize: number
|
||||
proxyEnabled: boolean
|
||||
proxyRequired: boolean
|
||||
proxyUrl: string
|
||||
proxyApi: string
|
||||
sharedProxyConfigFile: string
|
||||
@@ -32,6 +33,7 @@ export interface Settings {
|
||||
proxyWhitelistSignKey: string
|
||||
remoteEnabled: boolean
|
||||
remoteUrl: string
|
||||
remoteEnrollmentToken: string
|
||||
remoteToken: string
|
||||
remoteMachineName: string
|
||||
}
|
||||
@@ -55,19 +57,21 @@ const settings = ref<Settings>({
|
||||
seckillMode: 1,
|
||||
xiaodianPageSize: 200,
|
||||
proxyEnabled: false,
|
||||
proxyRequired: true,
|
||||
proxyUrl: '',
|
||||
proxyApi: '',
|
||||
sharedProxyConfigFile: '',
|
||||
proxyExpiresAt: 0,
|
||||
autoFetchProxyOnSchedule: false,
|
||||
accountsPerProxy: 5,
|
||||
proxySparePercent: 25,
|
||||
proxySparePercent: 50,
|
||||
proxyAutoWhitelist: false,
|
||||
proxyWhitelistReplace: true,
|
||||
proxyWhitelistPassword: '',
|
||||
proxyWhitelistSignKey: '',
|
||||
remoteEnabled: false,
|
||||
remoteUrl: '',
|
||||
remoteEnrollmentToken: '',
|
||||
remoteToken: '',
|
||||
remoteMachineName: ''
|
||||
})
|
||||
@@ -92,19 +96,21 @@ export function useSettings() {
|
||||
seckillMode: cfg.seckillMode ?? 1,
|
||||
xiaodianPageSize: cfg.xiaodianPageSize || 200,
|
||||
proxyEnabled: !!cfg.proxyEnabled,
|
||||
proxyRequired: !!cfg.proxyRequired,
|
||||
proxyUrl: cfg.proxyUrl || '',
|
||||
proxyApi: cfg.proxyApi || '',
|
||||
sharedProxyConfigFile: cfg.sharedProxyConfigFile || '',
|
||||
proxyExpiresAt: cfg.proxyExpiresAt || 0,
|
||||
autoFetchProxyOnSchedule: !!cfg.autoFetchProxyOnSchedule,
|
||||
accountsPerProxy: cfg.accountsPerProxy || 5,
|
||||
proxySparePercent: cfg.proxySparePercent || 25,
|
||||
proxySparePercent: cfg.proxySparePercent || 50,
|
||||
proxyAutoWhitelist: !!cfg.proxyAutoWhitelist,
|
||||
proxyWhitelistReplace: !!cfg.proxyWhitelistReplace,
|
||||
proxyWhitelistPassword: cfg.proxyWhitelistPassword || '',
|
||||
proxyWhitelistSignKey: cfg.proxyWhitelistSignKey || '',
|
||||
remoteEnabled: !!cfg.remoteEnabled,
|
||||
remoteUrl: cfg.remoteUrl || '',
|
||||
remoteEnrollmentToken: cfg.remoteEnrollmentToken || '',
|
||||
remoteToken: cfg.remoteToken || '',
|
||||
remoteMachineName: cfg.remoteMachineName || ''
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
|
||||
if cfg.AccountsPerProxy > constants.MaxAccountsPerProxy {
|
||||
cfg.AccountsPerProxy = constants.MaxAccountsPerProxy
|
||||
}
|
||||
if cfg.ProxySparePercent <= 0 {
|
||||
if cfg.ProxySparePercent < constants.MinProxySparePercent {
|
||||
cfg.ProxySparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if cfg.ProxySparePercent > constants.MaxProxySparePercent {
|
||||
@@ -119,6 +119,7 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
|
||||
cfg.LogLevel = "info"
|
||||
}
|
||||
cfg.RemoteURL = strings.TrimSpace(cfg.RemoteURL)
|
||||
cfg.RemoteEnrollmentToken = strings.TrimSpace(cfg.RemoteEnrollmentToken)
|
||||
cfg.RemoteToken = strings.TrimSpace(cfg.RemoteToken)
|
||||
cfg.RemoteMachineName = strings.TrimSpace(cfg.RemoteMachineName)
|
||||
if proxyURL := a.effectiveProxyURL(cfg); proxyURL != "" {
|
||||
@@ -175,6 +176,7 @@ func (a *App) SaveSettings(cfg types.Config) types.ErrorResult {
|
||||
a.scheduler.UpdateProxySettings(cfg)
|
||||
remoteChanged := cfg.RemoteEnabled != oldCfg.RemoteEnabled ||
|
||||
cfg.RemoteURL != oldCfg.RemoteURL ||
|
||||
cfg.RemoteEnrollmentToken != oldCfg.RemoteEnrollmentToken ||
|
||||
cfg.RemoteToken != oldCfg.RemoteToken ||
|
||||
cfg.RemoteMachineName != oldCfg.RemoteMachineName
|
||||
if remoteChanged {
|
||||
|
||||
@@ -148,7 +148,7 @@ func proxyDrillStandbyCount(activeCount, sparePercent int) int {
|
||||
if activeCount <= 0 {
|
||||
return 0
|
||||
}
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -195,7 +195,7 @@ func (a *App) extractProxyDrillPool(cfg types.Config, desired int) ([]proxyprovi
|
||||
}
|
||||
}
|
||||
if round < rounds-1 {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
time.Sleep(1200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
if len(endpoints) < desired {
|
||||
|
||||
@@ -11,21 +11,21 @@ import (
|
||||
)
|
||||
|
||||
func TestProxyDrillPlanAndTargets(t *testing.T) {
|
||||
if got := proxyDrillStandbyCount(6, 25); got != 2 {
|
||||
t.Fatalf("proxyDrillStandbyCount(6, 25)=%d, want 2", got)
|
||||
if got := proxyDrillStandbyCount(6, 50); got != 3 {
|
||||
t.Fatalf("proxyDrillStandbyCount(6, 50)=%d, want 3", got)
|
||||
}
|
||||
plan := proxyDrillPlan{accounts: 30, groupSize: 5, active: 6, standby: 2}
|
||||
endpoints := make([]proxyprovider.Endpoint, 8)
|
||||
plan := proxyDrillPlan{accounts: 30, groupSize: 5, active: 6, standby: 3}
|
||||
endpoints := make([]proxyprovider.Endpoint, 9)
|
||||
targets := buildProxyDrillTargets(plan, endpoints)
|
||||
if len(targets) != 8 {
|
||||
t.Fatalf("targets=%d, want 8", len(targets))
|
||||
if len(targets) != 9 {
|
||||
t.Fatalf("targets=%d, want 9", len(targets))
|
||||
}
|
||||
totalRequests := 0
|
||||
for _, target := range targets {
|
||||
totalRequests += target.requests
|
||||
}
|
||||
if totalRequests != 40 {
|
||||
t.Fatalf("totalRequests=%d, want 40 virtual requests", totalRequests)
|
||||
if totalRequests != 45 {
|
||||
t.Fatalf("totalRequests=%d, want 45 virtual requests", totalRequests)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,10 +18,14 @@ func (a *App) configureRemote(cfg types.Config) {
|
||||
}
|
||||
serverURL := strings.TrimSpace(cfg.RemoteURL)
|
||||
token := strings.TrimSpace(cfg.RemoteToken)
|
||||
enrollmentToken := strings.TrimSpace(cfg.RemoteEnrollmentToken)
|
||||
if serverURL == "" {
|
||||
logger.LogEvent("远端", "warn", "远端控制已启用,但控制中心地址为空")
|
||||
return
|
||||
}
|
||||
if token == "" && enrollmentToken == "" {
|
||||
logger.LogEvent("远端", "warn", "未填写注册令牌,仅能在控制中心自动注册窗口内首次连接")
|
||||
}
|
||||
machineID, err := remote.LoadOrCreateMachineID(a.paths.DataDir)
|
||||
if err != nil {
|
||||
logger.LogEvent("远端", "warn", "远端机器标识初始化失败: %v", err)
|
||||
@@ -32,14 +36,15 @@ func (a *App) configureRemote(cfg types.Config) {
|
||||
machineName, _ = os.Hostname()
|
||||
}
|
||||
agent, err := remote.NewAgent(remote.AgentOptions{
|
||||
DataDir: a.paths.DataDir,
|
||||
ServerURL: serverURL,
|
||||
Token: token,
|
||||
MachineID: machineID,
|
||||
MachineName: machineName,
|
||||
InstanceID: a.instanceName,
|
||||
Instance: a.instanceName,
|
||||
Version: a.GetVersion(),
|
||||
DataDir: a.paths.DataDir,
|
||||
ServerURL: serverURL,
|
||||
Token: token,
|
||||
EnrollmentToken: enrollmentToken,
|
||||
MachineID: machineID,
|
||||
MachineName: machineName,
|
||||
InstanceID: a.instanceName,
|
||||
Instance: a.instanceName,
|
||||
Version: a.GetVersion(),
|
||||
Snapshot: func() remote.Snapshot {
|
||||
scheduler := a.getScheduler()
|
||||
if scheduler == nil {
|
||||
@@ -50,6 +55,7 @@ func (a *App) configureRemote(cfg types.Config) {
|
||||
Running: scheduler.IsRunning(),
|
||||
Results: scheduler.Results(),
|
||||
AccountCount: scheduler.AccountCount(),
|
||||
ProxyStatus: proxyStatusPointer(scheduler.ProxyStatus()),
|
||||
}
|
||||
},
|
||||
Stop: func() error {
|
||||
@@ -77,6 +83,10 @@ func (a *App) configureRemote(cfg types.Config) {
|
||||
logger.LogEvent("远端", "info", "远端控制已启用: %s,机器=%s,实例=%s", serverURL, machineName, a.instanceName)
|
||||
}
|
||||
|
||||
func proxyStatusPointer(status types.ProxyStatusView) *types.ProxyStatusView {
|
||||
return &status
|
||||
}
|
||||
|
||||
func (a *App) closeRemote() {
|
||||
logger.SetObserver(nil)
|
||||
a.remoteMu.Lock()
|
||||
|
||||
@@ -28,6 +28,9 @@ func (a *App) StartSeckill(accountProducts map[string]string) types.MessageResul
|
||||
if err := a.scheduler.PrepareProxyGroups(accountProducts); err != nil {
|
||||
return types.MessageResult{Error: "代理准备失败: " + err.Error()}
|
||||
}
|
||||
if ok, reason := a.scheduler.ProxyRunGate(); !ok {
|
||||
return types.MessageResult{Error: "严格代理模式未就绪: " + reason}
|
||||
}
|
||||
if !a.scheduler.TryStartRun() {
|
||||
return types.MessageResult{Error: "抢购任务正在运行,请勿重复提交"}
|
||||
}
|
||||
@@ -81,6 +84,9 @@ func (a *App) startXiaodianSeckill(req types.FixedSeckillRequest, message string
|
||||
if err := a.scheduler.PrepareProxyGroups(req.AccountProducts); err != nil {
|
||||
return types.MessageResult{Error: "代理准备失败: " + err.Error()}
|
||||
}
|
||||
if ok, reason := a.scheduler.ProxyRunGate(); !ok {
|
||||
return types.MessageResult{Error: "严格代理模式未就绪: " + reason}
|
||||
}
|
||||
if !a.scheduler.TryStartRun() {
|
||||
return types.MessageResult{Error: "抢购任务正在运行,请勿重复提交"}
|
||||
}
|
||||
@@ -104,6 +110,14 @@ func (a *App) GetResults() map[string]string {
|
||||
return a.scheduler.Results()
|
||||
}
|
||||
|
||||
// GetProxyStatus returns the current instance proxy group and account mapping.
|
||||
func (a *App) GetProxyStatus() types.ProxyStatusView {
|
||||
if a.scheduler == nil {
|
||||
return types.ProxyStatusView{State: "disabled"}
|
||||
}
|
||||
return a.scheduler.ProxyStatus()
|
||||
}
|
||||
|
||||
// GetLogs 返回后端内存日志,支持增量获取。
|
||||
func (a *App) GetLogs(since int64) types.LogsResult {
|
||||
entries := a.logStore.Since(since)
|
||||
|
||||
@@ -175,6 +175,7 @@ func defaultConfig() types.Config {
|
||||
RetryStages: defaultRetryStages(),
|
||||
SeckillMode: types.SeckillModeAggressive,
|
||||
XiaodianPageSize: 200,
|
||||
ProxyRequired: true,
|
||||
AccountsPerProxy: constants.DefaultAccountsPerProxy,
|
||||
ProxySparePercent: constants.DefaultProxySparePercent,
|
||||
}
|
||||
@@ -240,6 +241,7 @@ func LoadConfig(path string) types.Config {
|
||||
|
||||
func normalizeRemoteConfig(cfg *types.Config) {
|
||||
cfg.RemoteURL = strings.TrimSpace(cfg.RemoteURL)
|
||||
cfg.RemoteEnrollmentToken = strings.TrimSpace(cfg.RemoteEnrollmentToken)
|
||||
cfg.RemoteToken = strings.TrimSpace(cfg.RemoteToken)
|
||||
cfg.RemoteMachineName = strings.TrimSpace(cfg.RemoteMachineName)
|
||||
}
|
||||
@@ -251,7 +253,7 @@ func normalizeProxyConfig(cfg *types.Config) {
|
||||
if cfg.AccountsPerProxy > constants.MaxAccountsPerProxy {
|
||||
cfg.AccountsPerProxy = constants.MaxAccountsPerProxy
|
||||
}
|
||||
if cfg.ProxySparePercent <= 0 {
|
||||
if cfg.ProxySparePercent < constants.MinProxySparePercent {
|
||||
cfg.ProxySparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if cfg.ProxySparePercent > constants.MaxProxySparePercent {
|
||||
|
||||
@@ -137,6 +137,12 @@ func TestLoadConfigNormalizesProxySparePercent(t *testing.T) {
|
||||
if got := LoadConfig(path).ProxySparePercent; got != constants.DefaultProxySparePercent {
|
||||
t.Fatalf("ProxySparePercent=%d, want %d", got, constants.DefaultProxySparePercent)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(`{"proxySparePercent":25}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := LoadConfig(path).ProxySparePercent; got != constants.MinProxySparePercent {
|
||||
t.Fatalf("legacy ProxySparePercent=%d, want minimum %d", got, constants.MinProxySparePercent)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(`{"proxySparePercent":999}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -145,6 +151,35 @@ func TestLoadConfigNormalizesProxySparePercent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigDefaultsToStrictProxyMode(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.json")
|
||||
if got := LoadConfig(path).ProxyRequired; !got {
|
||||
t.Fatal("new config should default to strict proxy mode")
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(`{}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := LoadConfig(path).ProxyRequired; !got {
|
||||
t.Fatal("legacy config without proxyRequired should inherit strict mode")
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(`{"proxyRequired":false}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := LoadConfig(path).ProxyRequired; got {
|
||||
t.Fatal("explicit proxyRequired=false should disable strict mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigNormalizesRemoteEnrollmentToken(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.json")
|
||||
if err := os.WriteFile(path, []byte(`{"remoteEnrollmentToken":" enroll-secret "}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := LoadConfig(path).RemoteEnrollmentToken; got != "enroll-secret" {
|
||||
t.Fatalf("RemoteEnrollmentToken=%q, want trimmed token", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadConfigMigratesLegacyTimeAPI(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.json")
|
||||
content := []byte(`{"timeApiUrl":"` + constants.LegacyDefaultTimeAPI + `"}`)
|
||||
|
||||
@@ -80,6 +80,9 @@ func ApplySharedProxyConfig(cfg *types.Config, shared types.SharedProxyConfig) {
|
||||
if proxy.Enabled != nil {
|
||||
cfg.ProxyEnabled = *proxy.Enabled
|
||||
}
|
||||
if proxy.Required != nil {
|
||||
cfg.ProxyRequired = *proxy.Required
|
||||
}
|
||||
if proxy.API != nil {
|
||||
cfg.ProxyAPI = strings.TrimSpace(*proxy.API)
|
||||
}
|
||||
@@ -111,6 +114,9 @@ func ApplySharedProxyConfig(cfg *types.Config, shared types.SharedProxyConfig) {
|
||||
if remote.URL != nil {
|
||||
cfg.RemoteURL = strings.TrimSpace(*remote.URL)
|
||||
}
|
||||
if remote.EnrollmentToken != nil {
|
||||
cfg.RemoteEnrollmentToken = strings.TrimSpace(*remote.EnrollmentToken)
|
||||
}
|
||||
if remote.Token != nil {
|
||||
cfg.RemoteToken = strings.TrimSpace(*remote.Token)
|
||||
}
|
||||
@@ -131,6 +137,7 @@ func SaveSharedProxyConfig(path string, cfg types.Config) error {
|
||||
UpdatedAt: time.Now().Format(time.RFC3339),
|
||||
Proxy: types.SharedProxySettings{
|
||||
Enabled: boolPointer(cfg.ProxyEnabled),
|
||||
Required: boolPointer(cfg.ProxyRequired),
|
||||
API: stringPointer(cfg.ProxyAPI),
|
||||
AccountsPerProxy: intPointer(cfg.AccountsPerProxy),
|
||||
SparePercent: intPointer(cfg.ProxySparePercent),
|
||||
@@ -141,10 +148,11 @@ func SaveSharedProxyConfig(path string, cfg types.Config) error {
|
||||
WhitelistSignKey: stringPointer(cfg.ProxyWhitelistSignKey),
|
||||
},
|
||||
Remote: types.SharedRemoteSettings{
|
||||
Enabled: boolPointer(cfg.RemoteEnabled),
|
||||
URL: stringPointer(cfg.RemoteURL),
|
||||
Token: stringPointer(cfg.RemoteToken),
|
||||
MachineName: stringPointer(cfg.RemoteMachineName),
|
||||
Enabled: boolPointer(cfg.RemoteEnabled),
|
||||
URL: stringPointer(cfg.RemoteURL),
|
||||
EnrollmentToken: stringPointer(cfg.RemoteEnrollmentToken),
|
||||
Token: stringPointer(cfg.RemoteToken),
|
||||
MachineName: stringPointer(cfg.RemoteMachineName),
|
||||
},
|
||||
}
|
||||
data, err := json.MarshalIndent(shared, "", " ")
|
||||
@@ -188,6 +196,7 @@ func SaveSharedProxyConfig(path string, cfg types.Config) error {
|
||||
|
||||
func hasSharedProxySettings(proxy types.SharedProxySettings) bool {
|
||||
return proxy.Enabled != nil ||
|
||||
proxy.Required != nil ||
|
||||
proxy.API != nil ||
|
||||
proxy.AccountsPerProxy != nil ||
|
||||
proxy.SparePercent != nil ||
|
||||
|
||||
@@ -13,10 +13,11 @@ func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "shared-proxy.json")
|
||||
cfg := types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyRequired: true,
|
||||
ProxyURL: "http://user:pass@127.0.0.1:9000",
|
||||
ProxyAPI: "https://service.ipzan.com/core-extract?mode=auth",
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
AutoFetchProxyOnSchedule: true,
|
||||
ProxyAutoWhitelist: true,
|
||||
ProxyWhitelistReplace: true,
|
||||
@@ -24,6 +25,7 @@ func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) {
|
||||
ProxyWhitelistSignKey: "0123456789abcdef",
|
||||
RemoteEnabled: true,
|
||||
RemoteURL: "https://control.example.com",
|
||||
RemoteEnrollmentToken: "enroll-token",
|
||||
RemoteToken: "remote-token",
|
||||
RemoteMachineName: "PC-01",
|
||||
}
|
||||
@@ -52,7 +54,14 @@ func TestSharedProxyConfigRoundTripExcludesRuntimeProxy(t *testing.T) {
|
||||
if !local.ProxyEnabled || local.ProxyAPI != cfg.ProxyAPI || local.AccountsPerProxy != 5 {
|
||||
t.Fatalf("unexpected merged config: %+v", local)
|
||||
}
|
||||
if local.ProxySparePercent != 50 {
|
||||
t.Fatalf("ProxySparePercent=%d, want 50", local.ProxySparePercent)
|
||||
}
|
||||
if !local.ProxyRequired {
|
||||
t.Fatal("ProxyRequired should round-trip through shared config")
|
||||
}
|
||||
if !local.RemoteEnabled || local.RemoteURL != cfg.RemoteURL ||
|
||||
local.RemoteEnrollmentToken != cfg.RemoteEnrollmentToken ||
|
||||
local.RemoteToken != cfg.RemoteToken || local.RemoteMachineName != cfg.RemoteMachineName {
|
||||
t.Fatalf("remote settings were not merged: %+v", local)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ const (
|
||||
DefaultConcurrency = 150
|
||||
DefaultAccountsPerProxy = 5
|
||||
MaxAccountsPerProxy = 100
|
||||
DefaultProxySparePercent = 25
|
||||
MinProxySparePercent = 50
|
||||
DefaultProxySparePercent = 50
|
||||
MaxProxySparePercent = 100
|
||||
ProductCacheTTL = 30 * time.Second
|
||||
|
||||
|
||||
@@ -98,7 +98,11 @@ func (p *GenericProvider) Parse(apiURL string, body []byte) ([]Endpoint, error)
|
||||
}
|
||||
|
||||
func isGenericFatalMessage(message string) bool {
|
||||
if strings.Contains(message, "提取频率过快") || strings.Contains(message, "请求过于频繁") {
|
||||
if strings.Contains(message, "提取频率过快") ||
|
||||
strings.Contains(message, "请求过于频繁") ||
|
||||
strings.Contains(message, "访问频率过快") ||
|
||||
strings.Contains(message, "白名单仅支持1秒") ||
|
||||
strings.Contains(message, "白名单仅支持 1 秒") {
|
||||
return false
|
||||
}
|
||||
for _, hint := range []string{
|
||||
|
||||
+55
-9
@@ -14,16 +14,20 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const whitelistRequestGap = 1200 * time.Millisecond
|
||||
|
||||
// IPZanProvider 接入品赞 https://service.ipzan.com/core-extract。
|
||||
type IPZanProvider struct {
|
||||
baseURL string
|
||||
now func() time.Time
|
||||
baseURL string
|
||||
now func() time.Time
|
||||
whitelistGap time.Duration
|
||||
}
|
||||
|
||||
func NewIPZanProvider() *IPZanProvider {
|
||||
return &IPZanProvider{
|
||||
baseURL: "https://service.ipzan.com",
|
||||
now: time.Now,
|
||||
baseURL: "https://service.ipzan.com",
|
||||
now: time.Now,
|
||||
whitelistGap: whitelistRequestGap,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +48,8 @@ func (p *IPZanProvider) RequestURL(apiURL string, count int) (string, error) {
|
||||
}
|
||||
query := u.Query()
|
||||
query.Set("num", strconv.Itoa(count))
|
||||
if strings.EqualFold(strings.TrimSpace(query.Get("mode")), "auth") {
|
||||
// txt 只返回 IP:端口,会丢失每个代理各自的账号密码,随后必然触发 407。
|
||||
query.Set("format", "json")
|
||||
}
|
||||
// JSON 才能保留每个代理独立的账号密码;txt 只返回 IP:端口,鉴权模式会触发 407。
|
||||
query.Set("format", "json")
|
||||
u.RawQuery = query.Encode()
|
||||
return u.String(), nil
|
||||
}
|
||||
@@ -160,6 +162,25 @@ func (p *IPZanProvider) AddWhitelist(ctx context.Context, httpClient *http.Clien
|
||||
if strings.TrimSpace(cfg.LoginPassword) == "" || strings.TrimSpace(cfg.SignKey) == "" {
|
||||
return &ProviderError{Provider: "品赞", Message: "自动白名单需要品赞登录密码和签名密钥", Fatal: true}
|
||||
}
|
||||
guard, err := acquireWhitelistLock(ctx, p.baseURL, no, cfg.IP)
|
||||
if err != nil {
|
||||
return fmt.Errorf("等待本机白名单协调锁失败: %w", err)
|
||||
}
|
||||
defer guard.release()
|
||||
if guard.recentlyAdded() {
|
||||
return nil
|
||||
}
|
||||
exists, err := p.verifyWhitelist(ctx, httpClient, no, cfg.IP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
guard.markAdded()
|
||||
return nil
|
||||
}
|
||||
if err := p.waitWhitelistSlot(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
sign, err := p.signWhitelist(cfg.LoginPassword, secret, cfg.SignKey)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -186,9 +207,24 @@ func (p *IPZanProvider) AddWhitelist(ctx context.Context, httpClient *http.Clien
|
||||
if err := p.doWhitelistRequest(req, httpClient, "添加白名单"); err != nil {
|
||||
return err
|
||||
}
|
||||
guard.markAdded()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *IPZanProvider) waitWhitelistSlot(ctx context.Context) error {
|
||||
if p.whitelistGap <= 0 {
|
||||
return nil
|
||||
}
|
||||
timer := time.NewTimer(p.whitelistGap)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *IPZanProvider) verifyWhitelist(ctx context.Context, httpClient *http.Client, no, ip string) (bool, error) {
|
||||
endpoint, err := url.Parse(strings.TrimRight(p.baseURL, "/") + "/whiteList-verify")
|
||||
if err != nil {
|
||||
@@ -297,7 +333,17 @@ func (p *IPZanProvider) doWhitelistRequestData(req *http.Request, httpClient *ht
|
||||
}
|
||||
|
||||
func isIPZanFatalMessage(message string) bool {
|
||||
if strings.Contains(message, "提取频率过快") {
|
||||
for _, retryable := range []string{
|
||||
"提取频率过快",
|
||||
"访问频率过快",
|
||||
"白名单仅支持1秒",
|
||||
"白名单仅支持 1 秒",
|
||||
} {
|
||||
if strings.Contains(message, retryable) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if strings.Contains(message, "白名单") && strings.Contains(message, "频繁") {
|
||||
return false
|
||||
}
|
||||
for _, hint := range []string{
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestIPZanRequestURLAlwaysUsesJSON(t *testing.T) {
|
||||
provider := NewIPZanProvider()
|
||||
raw := "https://service.ipzan.com/core-extract?mode=auth&format=txt&num=1"
|
||||
got, err := provider.RequestURL(raw, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(got)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format := u.Query().Get("format"); format != "json" {
|
||||
t.Fatalf("format=%q, want json", format)
|
||||
}
|
||||
if num := u.Query().Get("num"); num != "5" {
|
||||
t.Fatalf("num=%q, want 5", num)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPZanWhitelistRateLimitIsRetryable(t *testing.T) {
|
||||
for _, message := range []string{
|
||||
"访问频率过快,休息一下 白名单仅支持1秒访一次",
|
||||
"添加白名单失败: 访问频率过快",
|
||||
"提取频率过快",
|
||||
} {
|
||||
if isIPZanFatalMessage(message) {
|
||||
t.Fatalf("%q should be retryable", message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhitelistGuardSerializesAndRemembersSuccessfulAdd(t *testing.T) {
|
||||
const (
|
||||
baseURL = "https://example.test"
|
||||
no = "guard-test"
|
||||
ip = "203.0.113.99"
|
||||
)
|
||||
first, err := acquireWhitelistLock(context.Background(), baseURL, no, ip)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first.markAdded()
|
||||
t.Cleanup(func() {
|
||||
_ = os.Remove(first.path)
|
||||
_ = os.Remove(first.markerPath)
|
||||
})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond)
|
||||
defer cancel()
|
||||
if _, err := acquireWhitelistLock(ctx, baseURL, no, ip); err == nil {
|
||||
t.Fatal("second process should wait while the first guard is held")
|
||||
}
|
||||
first.release()
|
||||
|
||||
second, err := acquireWhitelistLock(context.Background(), baseURL, no, ip)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer second.release()
|
||||
if !second.recentlyAdded() {
|
||||
t.Fatal("successful whitelist add should be reused by sibling instances")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
const whitelistLockStaleAfter = 2 * time.Minute
|
||||
const whitelistMarkerTTL = 10 * time.Minute
|
||||
|
||||
type whitelistGuard struct {
|
||||
path string
|
||||
markerPath string
|
||||
}
|
||||
|
||||
func acquireWhitelistLock(ctx context.Context, baseURL, no, ip string) (*whitelistGuard, error) {
|
||||
sum := sha256.Sum256([]byte(baseURL + "\x00" + no + "\x00" + ip))
|
||||
dir := filepath.Join(os.TempDir(), "douyu-go-whitelist")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := hex.EncodeToString(sum[:16])
|
||||
path := filepath.Join(dir, key+".lock")
|
||||
guard := &whitelistGuard{
|
||||
path: path,
|
||||
markerPath: filepath.Join(dir, key+".ok"),
|
||||
}
|
||||
for {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
_, _ = fmt.Fprintf(file, "%d\n%s\n", os.Getpid(), time.Now().Format(time.RFC3339Nano))
|
||||
_ = file.Close()
|
||||
return guard, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrExist) {
|
||||
return nil, err
|
||||
}
|
||||
if info, statErr := os.Stat(path); statErr == nil && time.Since(info.ModTime()) > whitelistLockStaleAfter {
|
||||
_ = os.Remove(path)
|
||||
continue
|
||||
}
|
||||
timer := time.NewTimer(200 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (g *whitelistGuard) recentlyAdded() bool {
|
||||
if g == nil {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(g.markerPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
age := time.Since(info.ModTime())
|
||||
return age >= 0 && age < whitelistMarkerTTL
|
||||
}
|
||||
|
||||
func (g *whitelistGuard) markAdded() {
|
||||
if g == nil {
|
||||
return
|
||||
}
|
||||
_ = os.WriteFile(g.markerPath, []byte(time.Now().Format(time.RFC3339Nano)), 0o600)
|
||||
}
|
||||
|
||||
func (g *whitelistGuard) release() {
|
||||
if g != nil {
|
||||
_ = os.Remove(g.path)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -444,11 +443,7 @@ func cloneResults(source map[string]string) map[string]string {
|
||||
}
|
||||
|
||||
func agentWebSocketURL(raw string) (string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return "", errors.New("远端地址为空")
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
u, err := normalizeControlCenterURL(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -461,9 +456,7 @@ func agentWebSocketURL(raw string) (string, error) {
|
||||
default:
|
||||
return "", errors.New("远端地址必须以 http://、https://、ws:// 或 wss:// 开头")
|
||||
}
|
||||
if strings.TrimSpace(u.Path) == "" || u.Path == "/" {
|
||||
u.Path = "/ws/agent"
|
||||
}
|
||||
u.Path = "/ws/agent"
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ func enrollAgent(serverURL string, options AgentOptions) (string, error) {
|
||||
}
|
||||
|
||||
func enrollHTTPURL(raw string) (string, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
u, err := normalizeControlCenterURL(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -152,8 +152,33 @@ func enrollHTTPURL(raw string) (string, error) {
|
||||
default:
|
||||
return "", errors.New("远端地址协议无效")
|
||||
}
|
||||
if strings.TrimSpace(u.Path) == "" || u.Path == "/" {
|
||||
u.Path = "/api/enroll"
|
||||
}
|
||||
u.Path = "/api/enroll"
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func normalizeControlCenterURL(raw string) (*url.URL, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch strings.ToLower(u.Scheme) {
|
||||
case "http", "https", "ws", "wss":
|
||||
default:
|
||||
return nil, errors.New("远端地址必须以 http://、https://、ws:// 或 wss:// 开头")
|
||||
}
|
||||
if u.Host == "" {
|
||||
return nil, errors.New("远端地址缺少主机名")
|
||||
}
|
||||
if u.User != nil {
|
||||
return nil, errors.New("远端地址不能包含用户名或密码")
|
||||
}
|
||||
if u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, errors.New("远端地址不能包含查询参数或 #admin 管理令牌")
|
||||
}
|
||||
if path := strings.TrimRight(strings.TrimSpace(u.Path), "/"); path != "" {
|
||||
return nil, errors.New("远端地址必须是控制中心根地址,不能包含子路径")
|
||||
}
|
||||
u.Path = ""
|
||||
u.RawPath = ""
|
||||
return u, nil
|
||||
}
|
||||
|
||||
+17
-14
@@ -3,6 +3,8 @@ package remote
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"douyu_go/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -17,20 +19,21 @@ const (
|
||||
|
||||
// Snapshot is the latest state reported by one application instance.
|
||||
type Snapshot struct {
|
||||
MachineID string `json:"machineId"`
|
||||
MachineName string `json:"machineName"`
|
||||
InstanceID string `json:"instanceId"`
|
||||
InstanceName string `json:"instanceName"`
|
||||
Version string `json:"version"`
|
||||
ActivityID string `json:"activityId,omitempty"`
|
||||
State string `json:"state"`
|
||||
Running bool `json:"running"`
|
||||
RunID string `json:"runId,omitempty"`
|
||||
Results map[string]string `json:"results,omitempty"`
|
||||
AccountCount int `json:"accountCount"`
|
||||
QueuedEvents uint64 `json:"queuedEvents"`
|
||||
DroppedEvents uint64 `json:"droppedEvents"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
MachineID string `json:"machineId"`
|
||||
MachineName string `json:"machineName"`
|
||||
InstanceID string `json:"instanceId"`
|
||||
InstanceName string `json:"instanceName"`
|
||||
Version string `json:"version"`
|
||||
ActivityID string `json:"activityId,omitempty"`
|
||||
State string `json:"state"`
|
||||
Running bool `json:"running"`
|
||||
RunID string `json:"runId,omitempty"`
|
||||
Results map[string]string `json:"results,omitempty"`
|
||||
ProxyStatus *types.ProxyStatusView `json:"proxyStatus,omitempty"`
|
||||
AccountCount int `json:"accountCount"`
|
||||
QueuedEvents uint64 `json:"queuedEvents"`
|
||||
DroppedEvents uint64 `json:"droppedEvents"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// LogEvent is one structured event uploaded by an application instance.
|
||||
|
||||
@@ -34,6 +34,29 @@ func TestLoadOrCreateMachineIDSharedByInstances(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateServerURLRequiresControlCenterRoot(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
"https://control.example.com/#admin=secret",
|
||||
"https://control.example.com/control",
|
||||
"https://control.example.com/?token=secret",
|
||||
"https://user:pass@control.example.com",
|
||||
} {
|
||||
if err := ValidateServerURL(raw); err == nil {
|
||||
t.Fatalf("ValidateServerURL(%q) should fail", raw)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{
|
||||
"https://control.example.com",
|
||||
"https://control.example.com/",
|
||||
"http://127.0.0.1:18080",
|
||||
"wss://control.example.com",
|
||||
} {
|
||||
if err := ValidateServerURL(raw); err != nil {
|
||||
t.Fatalf("ValidateServerURL(%q): %v", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventSpoolPersistsOffset(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
spool, err := NewEventSpool(dir)
|
||||
@@ -209,6 +232,50 @@ func TestAgentAutoEnrollsWithoutManualToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentEnrollsWithConfiguredEnrollmentToken(t *testing.T) {
|
||||
server, err := NewServer(ServerOptions{
|
||||
DataDir: t.TempDir(),
|
||||
OperatorToken: "operator-token",
|
||||
EnrollToken: "enroll-secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
httpServer := httptest.NewServer(server.Handler())
|
||||
defer httpServer.Close()
|
||||
|
||||
dataDir := t.TempDir()
|
||||
agent, err := NewAgent(AgentOptions{
|
||||
DataDir: dataDir,
|
||||
ServerURL: httpServer.URL,
|
||||
EnrollmentToken: "enroll-secret",
|
||||
MachineID: "machine-secure",
|
||||
MachineName: "PC-SECURE",
|
||||
InstanceID: "实例 4",
|
||||
Instance: "实例 4",
|
||||
Version: "test",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
agent.Start(ctx)
|
||||
defer agent.Close()
|
||||
waitUntil(t, 5*time.Second, func() bool {
|
||||
instances := server.hub.Dashboard().Instances
|
||||
return len(instances) == 1 && instances[0].Online
|
||||
})
|
||||
token, err := loadAgentCredential(dataDir, httpServer.URL, "machine-secure", "实例 4")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if token == "" || token == "enroll-secret" {
|
||||
t.Fatalf("unexpected issued instance token %q", token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubAggregatesDynamicInstanceCount(t *testing.T) {
|
||||
hub, err := NewHub(t.TempDir())
|
||||
if err != nil {
|
||||
|
||||
@@ -310,6 +310,7 @@
|
||||
for (const item of instances) {
|
||||
machine.append(renderInstance(item));
|
||||
machine.append(renderResults(item));
|
||||
machine.append(renderProxyDetails(item));
|
||||
}
|
||||
machinesRoot.append(machine);
|
||||
}
|
||||
@@ -329,11 +330,17 @@
|
||||
const success = results.filter(value => String(value).startsWith('已抢到') || String(value).startsWith('成功') || String(value).includes('|积分-')).length;
|
||||
const resultCell = textNode('div', `结果 ${success}/${results.length || item.accountCount || 0}`);
|
||||
|
||||
const meta = textNode('div', `${item.accountCount || 0} 账号 · ${item.version || ''}`, 'muted');
|
||||
const proxy = item.proxyStatus;
|
||||
const proxyText = proxy?.enabled
|
||||
? `代理 ${proxy.activeCount || 0} · 备用 ${proxy.standbyCount || 0}/${proxy.standbyTarget || 0} · 直连 ${proxy.directCount || 0}`
|
||||
: '本地直连';
|
||||
const proxyWarning = ['direct_fallback', 'failed', 'degraded'].includes(proxy?.state);
|
||||
const meta = textNode('div', `${item.accountCount || 0} 账号 · ${proxyText}`, proxyWarning ? 'bad' : 'muted');
|
||||
|
||||
const actions = element('div', 'actions');
|
||||
actions.append(
|
||||
resultButton(item),
|
||||
proxyButton(item),
|
||||
logButton(item),
|
||||
commandButton(item, 'status', '刷新'),
|
||||
commandButton(item, 'stop', '停止', 'danger'),
|
||||
@@ -343,6 +350,42 @@
|
||||
return row;
|
||||
}
|
||||
|
||||
function renderProxyDetails(item) {
|
||||
const panel = element('div', 'results-details');
|
||||
panel.dataset.proxy = encodeURIComponent(`${item.machineId}:${item.instanceId}`);
|
||||
const proxy = item.proxyStatus;
|
||||
if (!proxy?.enabled) {
|
||||
panel.append(textNode('div', '当前实例未启用代理', 'muted'));
|
||||
return panel;
|
||||
}
|
||||
const summary = element('div', 'result-line');
|
||||
summary.append(
|
||||
textNode('span', `状态 ${proxy.state || 'unknown'}${proxy.required ? ' · 严格代理' : ''}`, ['direct_fallback', 'failed', 'degraded'].includes(proxy.state) ? 'bad' : 'ok'),
|
||||
textNode('span', `活动 ${proxy.activeCount || 0} · 备用 ${proxy.standbyCount || 0}/${proxy.standbyTarget || 0} · 直连 ${proxy.directCount || 0}`, 'muted')
|
||||
);
|
||||
panel.append(summary);
|
||||
for (const group of proxy.groups || []) {
|
||||
const line = element('div', 'result-line');
|
||||
line.append(
|
||||
textNode('span', `G${group.groupIndex} · ${group.accountCount || 0}号 · ${group.state || ''}`, group.state === 'direct' || group.state === 'failed' ? 'bad' : 'muted'),
|
||||
textNode('span', `${group.proxy || '-'} ${group.region ? '· ' + group.region : ''} ${group.rttMs ? '· ' + group.rttMs + 'ms' : ''} ${group.switchCount ? '· 切换 ' + group.switchCount : ''}`, 'muted')
|
||||
);
|
||||
panel.append(line);
|
||||
}
|
||||
if (proxy.lastError) panel.append(textNode('div', proxy.lastError, 'bad'));
|
||||
return panel;
|
||||
}
|
||||
|
||||
function proxyButton(item) {
|
||||
const button = element('button', '', '代理');
|
||||
button.addEventListener('click', () => {
|
||||
const key = encodeURIComponent(`${item.machineId}:${item.instanceId}`);
|
||||
const panel = machinesRoot.querySelector(`.results-details[data-proxy="${key}"]`);
|
||||
if (panel) panel.classList.toggle('open');
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function logButton(item) {
|
||||
const button = element('button', '', '日志');
|
||||
button.addEventListener('click', () => {
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
const (
|
||||
proxyFetchRounds = 3
|
||||
proxyFetchMaxRounds = 20
|
||||
proxyFetchRetryWait = 300 * time.Millisecond
|
||||
proxyFetchRetryWait = 1200 * time.Millisecond
|
||||
proxyRequestTimeout = 15 * time.Second
|
||||
proxyValidationTimeout = 3 * time.Second
|
||||
proxyValidationWorkers = 3
|
||||
@@ -38,6 +38,10 @@ type proxySettingsSnapshot struct {
|
||||
autoFetchOnTimer bool
|
||||
accountsPerProxy int
|
||||
sparePercent int
|
||||
required bool
|
||||
ready bool
|
||||
state string
|
||||
blockedReason string
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
@@ -55,8 +59,14 @@ type validatedProxy struct {
|
||||
}
|
||||
|
||||
type proxyRuntimeGroup struct {
|
||||
groupIndex int
|
||||
accountNames []string
|
||||
activeURL string
|
||||
activeIP string
|
||||
activeRegion string
|
||||
activeRTT time.Duration
|
||||
switchCount int
|
||||
lastError string
|
||||
consecutiveFailures int
|
||||
failed bool
|
||||
}
|
||||
@@ -90,13 +100,14 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
autoFetch := cfg.AutoFetchProxyOnSchedule
|
||||
accountsPerProxy := cfg.AccountsPerProxy
|
||||
sparePercent := cfg.ProxySparePercent
|
||||
required := cfg.ProxyRequired
|
||||
if accountsPerProxy <= 0 {
|
||||
accountsPerProxy = constants.DefaultAccountsPerProxy
|
||||
}
|
||||
if accountsPerProxy > constants.MaxAccountsPerProxy {
|
||||
accountsPerProxy = constants.MaxAccountsPerProxy
|
||||
}
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -113,6 +124,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
s.autoFetchProxyOnSchedule != autoFetch ||
|
||||
s.accountsPerProxy != accountsPerProxy ||
|
||||
s.proxySparePercent != sparePercent ||
|
||||
s.proxyRequired != required ||
|
||||
s.autoWhitelist != cfg.ProxyAutoWhitelist ||
|
||||
s.whitelistReplace != cfg.ProxyWhitelistReplace ||
|
||||
s.whitelistPassword != whitelistPassword ||
|
||||
@@ -123,6 +135,12 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
|
||||
s.autoFetchProxyOnSchedule = autoFetch
|
||||
s.accountsPerProxy = accountsPerProxy
|
||||
s.proxySparePercent = sparePercent
|
||||
s.proxyRequired = required
|
||||
if changed {
|
||||
s.proxyReady = false
|
||||
s.proxyState = "stale"
|
||||
s.proxyBlockedReason = "代理配置已变更,等待重新准备"
|
||||
}
|
||||
s.autoWhitelist = cfg.ProxyAutoWhitelist
|
||||
s.whitelistReplace = cfg.ProxyWhitelistReplace
|
||||
s.whitelistPassword = whitelistPassword
|
||||
@@ -149,7 +167,7 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
|
||||
size = constants.MaxAccountsPerProxy
|
||||
}
|
||||
sparePercent := s.proxySparePercent
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -162,6 +180,10 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
|
||||
autoFetchOnTimer: s.autoFetchProxyOnSchedule,
|
||||
accountsPerProxy: size,
|
||||
sparePercent: sparePercent,
|
||||
required: s.proxyRequired,
|
||||
ready: s.proxyReady,
|
||||
state: s.proxyState,
|
||||
blockedReason: s.proxyBlockedReason,
|
||||
autoWhitelist: s.autoWhitelist,
|
||||
whitelistReplace: s.whitelistReplace,
|
||||
whitelistPassword: s.whitelistPassword,
|
||||
@@ -180,6 +202,8 @@ func (s *Scheduler) closeAccountClients() {
|
||||
s.accountClientsDirty = true
|
||||
s.accountClientsExpireAt = time.Time{}
|
||||
s.proxyGroups = make(map[*client.DouyuClient]*proxyRuntimeGroup)
|
||||
s.proxyGroupHistory = nil
|
||||
s.accountProxyGroup = make(map[string]int)
|
||||
s.proxyStandbys = nil
|
||||
s.proxyClientPool = nil
|
||||
s.proxyExcludedURLs = make(map[string]struct{})
|
||||
@@ -211,6 +235,15 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
|
||||
s.accountClientsDirty = false
|
||||
s.accountClientsExpireAt = pool.expiresAt
|
||||
s.proxyGroups = pool.groups
|
||||
s.accountProxyGroup = make(map[string]int)
|
||||
for _, group := range pool.groups {
|
||||
if group == nil {
|
||||
continue
|
||||
}
|
||||
for _, name := range group.accountNames {
|
||||
s.accountProxyGroup[name] = group.groupIndex
|
||||
}
|
||||
}
|
||||
s.proxyStandbys = pool.standbys
|
||||
s.proxyClientPool = pool.allClients
|
||||
s.proxyExcludedURLs = pool.excludedURLs
|
||||
@@ -222,6 +255,146 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
|
||||
closeDouyuClientList(oldClients)
|
||||
}
|
||||
|
||||
func (s *Scheduler) replaceProxyGroupHistory(groups [][]string, activeCount int, proxies []validatedProxy) {
|
||||
history := make([]types.ProxyGroupStatus, 0, activeCount)
|
||||
for index, accounts := range groups {
|
||||
if index >= len(proxies) {
|
||||
break
|
||||
}
|
||||
proxy := proxies[index]
|
||||
history = append(history, types.ProxyGroupStatus{
|
||||
GroupIndex: index + 1,
|
||||
Role: "active",
|
||||
State: "active",
|
||||
AccountCount: len(accounts),
|
||||
Accounts: append([]string(nil), accounts...),
|
||||
Proxy: client.MaskProxyURL(proxy.url),
|
||||
Region: proxy.region,
|
||||
RTTMs: proxy.rtt.Milliseconds(),
|
||||
})
|
||||
}
|
||||
s.clientMu.Lock()
|
||||
s.proxyGroupHistory = history
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
// ProxyStatus returns a structured status snapshot. It never includes proxy
|
||||
// credentials and is safe to expose to the desktop and remote dashboards.
|
||||
func (s *Scheduler) ProxyStatus() types.ProxyStatusView {
|
||||
cfg := s.proxySettings()
|
||||
s.clientMu.RLock()
|
||||
history := make([]types.ProxyGroupStatus, len(s.proxyGroupHistory))
|
||||
copy(history, s.proxyGroupHistory)
|
||||
for i := range history {
|
||||
history[i].Accounts = append([]string(nil), history[i].Accounts...)
|
||||
}
|
||||
accountGroups := make(map[string]int, len(s.accountProxyGroup))
|
||||
for name, index := range s.accountProxyGroup {
|
||||
accountGroups[name] = index
|
||||
}
|
||||
names := make([]string, 0, len(s.accountClients))
|
||||
for name := range s.accountClients {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
groupsByIndex := make(map[int]types.ProxyGroupStatus, len(history))
|
||||
for _, group := range history {
|
||||
groupsByIndex[group.GroupIndex] = group
|
||||
}
|
||||
accounts := make([]types.AccountProxyView, 0, len(names))
|
||||
directCount := 0
|
||||
for _, name := range names {
|
||||
groupIndex := accountGroups[name]
|
||||
view := types.AccountProxyView{
|
||||
AccountName: name,
|
||||
GroupIndex: groupIndex,
|
||||
GroupLabel: "未分配",
|
||||
Transport: "unassigned",
|
||||
}
|
||||
if cli := s.accountClients[name]; cli == s.directClient {
|
||||
view.GroupLabel = "直连"
|
||||
view.Transport = "direct"
|
||||
directCount++
|
||||
} else if groupIndex > 0 {
|
||||
view.GroupLabel = fmt.Sprintf("G%d", groupIndex)
|
||||
view.Transport = "proxy"
|
||||
if group, ok := groupsByIndex[groupIndex]; ok {
|
||||
view.Proxy = group.Proxy
|
||||
}
|
||||
}
|
||||
accounts = append(accounts, view)
|
||||
}
|
||||
standbyCount := len(s.proxyStandbys)
|
||||
s.clientMu.RUnlock()
|
||||
|
||||
activeCount := 0
|
||||
for _, group := range history {
|
||||
if group.Role == "active" {
|
||||
activeCount++
|
||||
}
|
||||
}
|
||||
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
|
||||
state := cfg.state
|
||||
if state == "" {
|
||||
state = "empty"
|
||||
}
|
||||
lastError := cfg.blockedReason
|
||||
switch {
|
||||
case !cfg.enabled:
|
||||
state = "disabled"
|
||||
lastError = ""
|
||||
case directCount > 0:
|
||||
state = "direct_fallback"
|
||||
if lastError == "" {
|
||||
lastError = "账号已回退直连"
|
||||
}
|
||||
case cfg.ready:
|
||||
state = "ready"
|
||||
lastError = ""
|
||||
if reason := proxyDegradedReason(history, standbyCount, standbyTarget); reason != "" {
|
||||
state = "degraded"
|
||||
lastError = reason
|
||||
}
|
||||
case state == "preparing":
|
||||
// Keep the explicit preparing state visible while the pool is refreshed.
|
||||
case lastError != "":
|
||||
state = "failed"
|
||||
case len(history) == 0:
|
||||
state = "empty"
|
||||
default:
|
||||
state = "preparing"
|
||||
}
|
||||
return types.ProxyStatusView{
|
||||
Enabled: cfg.enabled,
|
||||
Required: cfg.required,
|
||||
State: state,
|
||||
ActiveCount: activeCount,
|
||||
StandbyCount: standbyCount,
|
||||
StandbyTarget: standbyTarget,
|
||||
DirectCount: directCount,
|
||||
LastError: lastError,
|
||||
UpdatedAt: time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000"),
|
||||
Groups: history,
|
||||
Accounts: accounts,
|
||||
}
|
||||
}
|
||||
|
||||
func proxyDegradedReason(groups []types.ProxyGroupStatus, standbyCount, standbyTarget int) string {
|
||||
failed := 0
|
||||
for _, group := range groups {
|
||||
if group.State == "failed" {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
if failed > 0 {
|
||||
return fmt.Sprintf("%d 个代理组失败,等待备用代理", failed)
|
||||
}
|
||||
if standbyCount < standbyTarget {
|
||||
return fmt.Sprintf("备用代理不足: %d/%d", standbyCount, standbyTarget)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func closeDouyuClients(clients map[string]*client.DouyuClient) {
|
||||
items := make([]*client.DouyuClient, 0, len(clients))
|
||||
for _, cli := range clients {
|
||||
@@ -318,6 +491,14 @@ func (s *Scheduler) allClients() []*client.DouyuClient {
|
||||
// prepareProxyGroups 将本次参与抢购的账号按固定顺序分组,并为每组准备独立客户端。
|
||||
// forceRefresh=true 用于定时任务启动前主动刷新短效代理。
|
||||
func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceRefresh bool) error {
|
||||
timeout := proxyImmediateTimeout
|
||||
if forceRefresh {
|
||||
timeout = proxyScheduledTimeout
|
||||
}
|
||||
return s.prepareProxyGroupsUntil(accountProducts, forceRefresh, time.Now().Add(timeout))
|
||||
}
|
||||
|
||||
func (s *Scheduler) prepareProxyGroupsUntil(accountProducts map[string]string, forceRefresh bool, deadline time.Time) error {
|
||||
s.proxyPrepareMu.Lock()
|
||||
defer s.proxyPrepareMu.Unlock()
|
||||
|
||||
@@ -328,38 +509,38 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
}
|
||||
if !cfg.enabled {
|
||||
s.closeAccountClients()
|
||||
s.setProxyReadiness(false, "代理未启用")
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.proxyFallbackSnapshot() {
|
||||
if !forceRefresh && !cfg.required && s.proxyFallbackSnapshot() {
|
||||
logger.LogEvent("代理", "warn", "代理此前准备失败,本次抢购直接使用直连,避免再次等待")
|
||||
return nil
|
||||
}
|
||||
if !forceRefresh && s.accountClientsCover(names) {
|
||||
s.setProxyReadiness(true, "")
|
||||
return nil
|
||||
}
|
||||
s.setProxyPreparing("代理正在准备")
|
||||
|
||||
groups := chunkAccountNames(names, cfg.accountsPerProxy)
|
||||
activeCount := len(groups)
|
||||
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
|
||||
base := s.clientSnapshot()
|
||||
if base == nil {
|
||||
s.activateProxyDirectFallback(errors.New("基础客户端未初始化"))
|
||||
return nil
|
||||
return s.handleProxyPrepareFailure(cfg, names, errors.New("基础客户端未初始化"))
|
||||
}
|
||||
|
||||
poolStartedAt := time.Now()
|
||||
timeout := proxyImmediateTimeout
|
||||
if forceRefresh {
|
||||
timeout = proxyScheduledTimeout
|
||||
timeout := time.Until(deadline)
|
||||
if timeout <= 0 {
|
||||
return s.handleProxyPrepareFailure(cfg, names, errors.New("代理准备截止时间已到"))
|
||||
}
|
||||
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil, timeout)
|
||||
if err != nil {
|
||||
s.activateProxyDirectFallback(err)
|
||||
return nil
|
||||
return s.handleProxyPrepareFailure(cfg, names, err)
|
||||
}
|
||||
if len(proxies) < activeCount {
|
||||
s.activateProxyDirectFallback(fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
|
||||
return nil
|
||||
closeValidatedProxies(proxies)
|
||||
return s.handleProxyPrepareFailure(cfg, names, fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
|
||||
}
|
||||
if len(proxies) < activeCount+standbyTarget {
|
||||
logger.LogEvent("代理", "warn", "备用代理不足: 目标%d个,实际%d个;活动代理不受影响",
|
||||
@@ -373,8 +554,12 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
proxy := proxies[i]
|
||||
clientOrder = append(clientOrder, proxy.client)
|
||||
runtimeGroups[proxy.client] = &proxyRuntimeGroup{
|
||||
groupIndex: i + 1,
|
||||
accountNames: append([]string(nil), group...),
|
||||
activeURL: proxy.url,
|
||||
activeIP: proxy.ip,
|
||||
activeRegion: proxy.region,
|
||||
activeRTT: proxy.rtt,
|
||||
}
|
||||
for _, name := range group {
|
||||
accountClients[name] = proxy.client
|
||||
@@ -394,6 +579,7 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
s.recordProxyResult(proxyClient, err)
|
||||
})
|
||||
}
|
||||
poolStartedAt := time.Now()
|
||||
expiresAt := time.Time{}
|
||||
if cfg.proxyAPI != "" {
|
||||
expiresAt = proxyPoolExpiresAt(cfg.proxyAPI, poolStartedAt)
|
||||
@@ -416,11 +602,60 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
|
||||
standbyTarget: effectiveProxyStandbyTarget(cfg, standbyTarget, len(standbys)),
|
||||
expiresAt: expiresAt,
|
||||
})
|
||||
s.replaceProxyGroupHistory(groups, activeCount, proxies)
|
||||
logger.LogEvent("代理", "success", "代理池准备完成: 账号=%d,每组=%d,活动代理=%d,备用代理=%d/%d",
|
||||
len(names), cfg.accountsPerProxy, activeCount, len(standbys), standbyTarget)
|
||||
s.setProxyReadiness(true, "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) handleProxyPrepareFailure(cfg proxySettingsSnapshot, names []string, cause error) error {
|
||||
if cfg.required {
|
||||
s.closeAccountClients()
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "error", "严格代理模式准备失败,本次不启动且不回退直连: %v", cause)
|
||||
return cause
|
||||
}
|
||||
s.activateProxyDirectFallback(cause)
|
||||
s.setDirectFallbackAccounts(names)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) setDirectFallbackAccounts(names []string) {
|
||||
s.clientMu.Lock()
|
||||
if s.directClient != nil {
|
||||
s.accountClients = make(map[string]*client.DouyuClient, len(names))
|
||||
for _, name := range names {
|
||||
s.accountClients[name] = s.directClient
|
||||
}
|
||||
s.accountClientOrder = []*client.DouyuClient{s.directClient}
|
||||
s.accountClientsDirty = false
|
||||
}
|
||||
s.clientMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) setProxyReadiness(ready bool, reason string) {
|
||||
s.proxyMu.Lock()
|
||||
s.proxyReady = ready
|
||||
if ready {
|
||||
s.proxyState = "ready"
|
||||
} else if reason != "" {
|
||||
s.proxyState = "failed"
|
||||
} else {
|
||||
s.proxyState = "empty"
|
||||
}
|
||||
s.proxyBlockedReason = reason
|
||||
s.proxyMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) setProxyPreparing(reason string) {
|
||||
s.proxyMu.Lock()
|
||||
s.proxyReady = false
|
||||
s.proxyState = "preparing"
|
||||
s.proxyBlockedReason = reason
|
||||
s.proxyMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Scheduler) proxyFallbackSnapshot() bool {
|
||||
s.clientMu.RLock()
|
||||
defer s.clientMu.RUnlock()
|
||||
@@ -434,9 +669,11 @@ func (s *Scheduler) activateProxyDirectFallback(cause error) {
|
||||
s.proxyFallbackActive = active
|
||||
s.clientMu.Unlock()
|
||||
if active {
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "warn", "代理准备失败,已回退直连以保证抢购继续: %v", cause)
|
||||
return
|
||||
}
|
||||
s.setProxyReadiness(false, cause.Error())
|
||||
logger.LogEvent("代理", "error", "代理准备失败且直连客户端不可用: %v", cause)
|
||||
}
|
||||
|
||||
@@ -452,6 +689,10 @@ func (s *Scheduler) PrepareProxyGroups(accountProducts map[string]string) error
|
||||
return s.prepareProxyGroups(accountProducts, false)
|
||||
}
|
||||
|
||||
func (s *Scheduler) PrepareProxyGroupsUntil(accountProducts map[string]string, deadline time.Time) error {
|
||||
return s.prepareProxyGroupsUntil(accountProducts, true, deadline)
|
||||
}
|
||||
|
||||
func selectedAccountNames(accountProducts map[string]string) []string {
|
||||
names := make([]string, 0, len(accountProducts))
|
||||
for name, productID := range accountProducts {
|
||||
@@ -487,7 +728,7 @@ func proxyStandbyCount(activeCount, sparePercent int) int {
|
||||
if activeCount <= 0 {
|
||||
return 0
|
||||
}
|
||||
if sparePercent <= 0 {
|
||||
if sparePercent < constants.MinProxySparePercent {
|
||||
sparePercent = constants.DefaultProxySparePercent
|
||||
}
|
||||
if sparePercent > constants.MaxProxySparePercent {
|
||||
@@ -726,6 +967,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
if proxyClient == nil {
|
||||
return
|
||||
}
|
||||
cfg := s.proxySettings()
|
||||
|
||||
s.clientMu.Lock()
|
||||
group := s.proxyGroups[proxyClient]
|
||||
@@ -735,6 +977,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
if err == nil {
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
s.clientMu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -744,6 +988,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
|
||||
group.consecutiveFailures++
|
||||
group.lastError = err.Error()
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
if group.consecutiveFailures < 2 {
|
||||
failures := group.consecutiveFailures
|
||||
activeURL := group.activeURL
|
||||
@@ -753,7 +999,9 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
}
|
||||
|
||||
event, expiredClients, switched := s.switchGroupToStandbyLocked(proxyClient, group)
|
||||
if !switched && s.directClient != nil {
|
||||
if !switched && cfg.required {
|
||||
group.failed = true
|
||||
} else if !switched && s.directClient != nil {
|
||||
event = s.switchGroupToDirectLocked(proxyClient, group)
|
||||
switched = true
|
||||
}
|
||||
@@ -767,6 +1015,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
failedAccounts = len(group.accountNames)
|
||||
failedURL = group.activeURL
|
||||
needRefill = !s.proxyRefillInFlight
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
}
|
||||
s.clientMu.Unlock()
|
||||
|
||||
@@ -774,8 +1023,13 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
|
||||
if switched {
|
||||
logProxySwitch("代理故障切换", event)
|
||||
} else {
|
||||
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
if cfg.required {
|
||||
logger.LogEvent("代理", "warn", "严格代理模式下代理组连续失败且暂无备用,暂不直连并等待补提取: 账号=%d 出口=%s",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
} else {
|
||||
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
|
||||
failedAccounts, client.MaskProxyURL(failedURL))
|
||||
}
|
||||
}
|
||||
if needRefill {
|
||||
s.startProxyRefill()
|
||||
@@ -802,7 +1056,12 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
|
||||
toSource: standby.source,
|
||||
}
|
||||
group.activeURL = standby.url
|
||||
group.activeIP = standby.ip
|
||||
group.activeRegion = standby.region
|
||||
group.activeRTT = standby.rtt
|
||||
group.switchCount++
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
group.failed = false
|
||||
for _, accountName := range group.accountNames {
|
||||
s.accountClients[accountName] = standby.client
|
||||
@@ -810,6 +1069,7 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
|
||||
delete(s.proxyGroups, oldClient)
|
||||
s.proxyGroups[standby.client] = group
|
||||
replaceClientInOrder(s.accountClientOrder, oldClient, standby.client)
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
return event, expiredClients, true
|
||||
}
|
||||
return proxySwitchEvent{}, expiredClients, false
|
||||
@@ -821,16 +1081,52 @@ func (s *Scheduler) switchGroupToDirectLocked(oldClient *client.DouyuClient, gro
|
||||
fromURL: group.activeURL,
|
||||
}
|
||||
group.activeURL = ""
|
||||
group.activeIP = ""
|
||||
group.activeRegion = ""
|
||||
group.activeRTT = 0
|
||||
group.switchCount++
|
||||
group.consecutiveFailures = 0
|
||||
group.lastError = ""
|
||||
group.failed = false
|
||||
for _, accountName := range group.accountNames {
|
||||
s.accountClients[accountName] = s.directClient
|
||||
}
|
||||
delete(s.proxyGroups, oldClient)
|
||||
replaceClientInOrder(s.accountClientOrder, oldClient, s.directClient)
|
||||
s.updateProxyGroupHistoryLocked(group)
|
||||
return event
|
||||
}
|
||||
|
||||
func (s *Scheduler) updateProxyGroupHistoryLocked(group *proxyRuntimeGroup) {
|
||||
if group == nil || group.groupIndex <= 0 {
|
||||
return
|
||||
}
|
||||
for i := range s.proxyGroupHistory {
|
||||
item := &s.proxyGroupHistory[i]
|
||||
if item.GroupIndex != group.groupIndex {
|
||||
continue
|
||||
}
|
||||
item.AccountCount = len(group.accountNames)
|
||||
item.Accounts = append([]string(nil), group.accountNames...)
|
||||
item.SwitchCount = group.switchCount
|
||||
item.LastError = group.lastError
|
||||
switch {
|
||||
case group.activeURL == "":
|
||||
item.State = "direct"
|
||||
item.Proxy = ""
|
||||
item.Region = ""
|
||||
case group.failed:
|
||||
item.State = "failed"
|
||||
default:
|
||||
item.State = "active"
|
||||
item.Proxy = client.MaskProxyURL(group.activeURL)
|
||||
item.Region = group.activeRegion
|
||||
item.RTTMs = group.activeRTT.Milliseconds()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func replaceClientInOrder(order []*client.DouyuClient, oldClient, newClient *client.DouyuClient) {
|
||||
for i, cli := range order {
|
||||
if cli == oldClient {
|
||||
|
||||
@@ -47,10 +47,10 @@ func TestProxyStandbyCount(t *testing.T) {
|
||||
percent int
|
||||
want int
|
||||
}{
|
||||
{active: 1, percent: 25, want: 1},
|
||||
{active: 6, percent: 25, want: 2},
|
||||
{active: 10, percent: 25, want: 3},
|
||||
{active: 6, percent: 1, want: 1},
|
||||
{active: 1, percent: 50, want: 1},
|
||||
{active: 6, percent: 50, want: 3},
|
||||
{active: 10, percent: 50, want: 5},
|
||||
{active: 6, percent: 1, want: 3},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := proxyStandbyCount(tc.active, tc.percent); got != tc.want {
|
||||
@@ -59,6 +59,26 @@ func TestProxyStandbyCount(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestShouldPrepareProxyOnSchedule(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
cfg proxySettingsSnapshot
|
||||
want bool
|
||||
}{
|
||||
{name: "disabled", cfg: proxySettingsSnapshot{required: true}, want: false},
|
||||
{name: "strict static", cfg: proxySettingsSnapshot{enabled: true, required: true}, want: true},
|
||||
{name: "auto fetch api", cfg: proxySettingsSnapshot{enabled: true, autoFetchOnTimer: true, proxyAPI: "https://example.test"}, want: true},
|
||||
{name: "optional api without auto fetch", cfg: proxySettingsSnapshot{enabled: true, proxyAPI: "https://example.test"}, want: false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := shouldPrepareProxyOnSchedule(tc.cfg); got != tc.want {
|
||||
t.Fatalf("shouldPrepareProxyOnSchedule()=%v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountClientsRespectExpiryAndSettingsRevision(t *testing.T) {
|
||||
scheduler := &Scheduler{
|
||||
client: &client.DouyuClient{},
|
||||
@@ -105,7 +125,7 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
ProxyAPI: apiServer.URL,
|
||||
AutoFetchProxyOnSchedule: true,
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
|
||||
accountProducts := make(map[string]string)
|
||||
@@ -128,8 +148,8 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
if scheduler.clientForAccount("e") == scheduler.clientForAccount("a") {
|
||||
t.Fatal("e 应使用独立代理客户端")
|
||||
}
|
||||
if len(scheduler.proxyStandbys) != 1 {
|
||||
t.Fatalf("备用代理=%d, want 1", len(scheduler.proxyStandbys))
|
||||
if len(scheduler.proxyStandbys) != 2 {
|
||||
t.Fatalf("备用代理=%d, want 2", len(scheduler.proxyStandbys))
|
||||
}
|
||||
|
||||
standbyClient := scheduler.proxyStandbys[0].client
|
||||
@@ -137,7 +157,7 @@ func TestPrepareProxyGroupsRoutesAccountsToDistinctClients(t *testing.T) {
|
||||
ProxyEnabled: true,
|
||||
ProxyURL: "http://127.0.0.1:1",
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
proxyErr := errors.New("read tcp: connection reset by peer")
|
||||
scheduler.recordProxyResult(scheduler.clientForAccount("a"), proxyErr)
|
||||
@@ -169,7 +189,7 @@ func TestPrepareProxyGroupsFallsBackDirectAndSkipsRepeatedWait(t *testing.T) {
|
||||
ProxyEnabled: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 25,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
accountProducts := map[string]string{"a": "goods-1"}
|
||||
|
||||
@@ -218,6 +238,123 @@ func TestProxyGroupSwitchesDirectWhenStandbyUnavailable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictProxyModeDoesNotSwitchDirect(t *testing.T) {
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyRequired: true,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
groupClient := &client.DouyuClient{}
|
||||
group := &proxyRuntimeGroup{
|
||||
groupIndex: 1,
|
||||
accountNames: []string{"a"},
|
||||
activeURL: "http://user:pass@127.0.0.1:9000",
|
||||
}
|
||||
scheduler.replaceAccountClients(preparedProxyPool{
|
||||
accountClients: map[string]*client.DouyuClient{"a": groupClient},
|
||||
activeClients: []*client.DouyuClient{groupClient},
|
||||
groups: map[*client.DouyuClient]*proxyRuntimeGroup{groupClient: group},
|
||||
allClients: []*client.DouyuClient{groupClient},
|
||||
})
|
||||
scheduler.replaceProxyGroupHistory([][]string{{"a"}}, 1, []validatedProxy{{
|
||||
url: group.activeURL,
|
||||
client: groupClient,
|
||||
}})
|
||||
|
||||
proxyErr := errors.New("read tcp: connection reset by peer")
|
||||
scheduler.recordProxyResult(groupClient, proxyErr)
|
||||
scheduler.recordProxyResult(groupClient, proxyErr)
|
||||
if scheduler.clientForAccount("a") == scheduler.directClient {
|
||||
t.Fatal("strict proxy mode must not switch to direct")
|
||||
}
|
||||
if !group.failed {
|
||||
t.Fatal("failed group should remain tracked for standby refill")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyStatusReportsGroupAndAccountMapping(t *testing.T) {
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
AccountsPerProxy: 2,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
groupClient := &client.DouyuClient{}
|
||||
group := &proxyRuntimeGroup{
|
||||
groupIndex: 1,
|
||||
accountNames: []string{"a", "b"},
|
||||
activeURL: "http://user:pass@127.0.0.1:9000",
|
||||
activeIP: "127.0.0.1",
|
||||
activeRegion: "test",
|
||||
activeRTT: 45 * time.Millisecond,
|
||||
}
|
||||
standbyClient := &client.DouyuClient{}
|
||||
scheduler.replaceAccountClients(preparedProxyPool{
|
||||
accountClients: map[string]*client.DouyuClient{"a": groupClient, "b": groupClient},
|
||||
activeClients: []*client.DouyuClient{groupClient},
|
||||
groups: map[*client.DouyuClient]*proxyRuntimeGroup{groupClient: group},
|
||||
standbys: []validatedProxy{{client: standbyClient}},
|
||||
allClients: []*client.DouyuClient{groupClient, standbyClient},
|
||||
standbyTarget: 1,
|
||||
})
|
||||
scheduler.replaceProxyGroupHistory([][]string{{"a", "b"}}, 1, []validatedProxy{{
|
||||
url: group.activeURL,
|
||||
client: groupClient,
|
||||
ip: group.activeIP,
|
||||
region: group.activeRegion,
|
||||
rtt: group.activeRTT,
|
||||
}})
|
||||
scheduler.setProxyReadiness(true, "")
|
||||
|
||||
status := scheduler.ProxyStatus()
|
||||
if status.State != "ready" || status.ActiveCount != 1 || len(status.Groups) != 1 {
|
||||
t.Fatalf("unexpected status: %+v", status)
|
||||
}
|
||||
if len(status.Accounts) != 2 || status.Accounts[0].GroupLabel != "G1" || status.Accounts[0].Transport != "proxy" {
|
||||
t.Fatalf("unexpected account mapping: %+v", status.Accounts)
|
||||
}
|
||||
if status.Groups[0].Proxy == "" || status.Groups[0].Proxy == group.activeURL {
|
||||
t.Fatalf("proxy URL should be masked, got %q", status.Groups[0].Proxy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictPrepareFailureBlocksRun(t *testing.T) {
|
||||
apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"code":-1,"status":200,"message":"secret密匙错误"}`)
|
||||
}))
|
||||
defer apiServer.Close()
|
||||
act := *activity.Get("peace")
|
||||
base := client.New(&act, "http://douyu.test/time", &trace.Recorder{}, "")
|
||||
scheduler := New(base, types.AppPaths{}, nil, 8, 1, nil, types.SeckillModeAggressive)
|
||||
scheduler.UpdateProxySettings(types.Config{
|
||||
ProxyEnabled: true,
|
||||
ProxyRequired: true,
|
||||
ProxyAPI: apiServer.URL,
|
||||
AccountsPerProxy: 5,
|
||||
ProxySparePercent: 50,
|
||||
})
|
||||
err := scheduler.prepareProxyGroupsUntil(map[string]string{"a": "goods-1"}, false, time.Now().Add(2*time.Second))
|
||||
if err == nil {
|
||||
t.Fatal("strict proxy preparation should fail")
|
||||
}
|
||||
if scheduler.proxyFallbackSnapshot() {
|
||||
t.Fatal("strict mode must not activate direct fallback")
|
||||
}
|
||||
if ok, _ := scheduler.ProxyRunGate(); ok {
|
||||
t.Fatal("strict mode run gate should remain closed")
|
||||
}
|
||||
if status := scheduler.ProxyStatus(); status.State != "failed" {
|
||||
t.Fatalf("proxy status=%q, want failed", status.State)
|
||||
}
|
||||
}
|
||||
|
||||
func newTimeProxyServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -48,7 +48,7 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
|
||||
proxyCfg := s.proxySettings()
|
||||
|
||||
if proxyCfg.enabled && proxyCfg.autoFetchOnTimer && proxyCfg.proxyAPI != "" {
|
||||
if shouldPrepareProxyOnSchedule(proxyCfg) {
|
||||
proxyFetchRemain := triggerTime.Sub(serverTime) - proxyFetchBeforeTrigger
|
||||
if proxyFetchRemain < 0 {
|
||||
proxyFetchRemain = 0
|
||||
@@ -58,8 +58,10 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
if s.IsRunning() {
|
||||
return
|
||||
}
|
||||
logger.LogEvent("代理", "info", "定时任务触发前,自动提取并校验分组代理...")
|
||||
if err := s.prepareProxyGroups(ap, true); err != nil {
|
||||
deadline := triggerTime.Add(-proxyReadyDeadline)
|
||||
logger.LogEvent("代理", "info", "定时任务触发前 2 分钟,开始提取并校验分组代理,截止=%s",
|
||||
deadline.In(constants.CST).Format("15:04:05.000"))
|
||||
if err := s.prepareProxyGroupsUntil(ap, true, deadline); err != nil {
|
||||
logger.LogEvent("代理", "error", "定时分组代理准备失败: %v", err)
|
||||
return
|
||||
}
|
||||
@@ -120,6 +122,13 @@ func (s *Scheduler) ScheduleRun(req types.SeckillRequest) (types.ScheduleResult,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func shouldPrepareProxyOnSchedule(cfg proxySettingsSnapshot) bool {
|
||||
if !cfg.enabled {
|
||||
return false
|
||||
}
|
||||
return cfg.required || (cfg.autoFetchOnTimer && cfg.proxyAPI != "")
|
||||
}
|
||||
|
||||
func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime, triggerTime time.Time, calibration types.TimeCalibration, attempts, delayMs int, resync bool) {
|
||||
serverTime := calibration.EstimatedServerNow()
|
||||
remain := triggerTime.Sub(serverTime)
|
||||
@@ -154,6 +163,10 @@ func (s *Scheduler) scheduleTimers(accountProducts map[string]string, targetTime
|
||||
estimatedServer.In(constants.CST).Format("15:04:05.000"),
|
||||
calibration.Offset.Milliseconds(),
|
||||
calibration.ErrorBound.Milliseconds())
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次定时抢购不启动: %s", reason)
|
||||
return
|
||||
}
|
||||
if !s.TryStartRun() {
|
||||
logger.LogEvent("抢购", "warn", "已有抢购任务正在运行,本次定时触发已跳过")
|
||||
return
|
||||
|
||||
@@ -28,7 +28,8 @@ const (
|
||||
timeCalibrateRounds = 3
|
||||
timeCalibrateWait = 1200 * time.Millisecond
|
||||
resyncBeforeTrigger = 8 * time.Second
|
||||
proxyFetchBeforeTrigger = 30 * time.Second
|
||||
proxyFetchBeforeTrigger = 120 * time.Second
|
||||
proxyReadyDeadline = 15 * time.Second
|
||||
calibrationHistorySize = 3
|
||||
maxCooldownCount = 5
|
||||
xiaodianDefaultDelay = 500 * time.Millisecond
|
||||
@@ -68,6 +69,8 @@ type Scheduler struct {
|
||||
accountClientsDirty bool
|
||||
accountClientsExpireAt time.Time
|
||||
proxyGroups map[*client.DouyuClient]*proxyRuntimeGroup
|
||||
proxyGroupHistory []types.ProxyGroupStatus
|
||||
accountProxyGroup map[string]int
|
||||
proxyStandbys []validatedProxy
|
||||
proxyClientPool []*client.DouyuClient
|
||||
proxyExcludedURLs map[string]struct{}
|
||||
@@ -120,6 +123,10 @@ type Scheduler struct {
|
||||
autoFetchProxyOnSchedule bool
|
||||
accountsPerProxy int
|
||||
proxySparePercent int
|
||||
proxyRequired bool
|
||||
proxyReady bool
|
||||
proxyState string
|
||||
proxyBlockedReason string
|
||||
autoWhitelist bool
|
||||
whitelistReplace bool
|
||||
whitelistPassword string
|
||||
@@ -465,6 +472,23 @@ func (s *Scheduler) IsRunning() bool {
|
||||
return s.running
|
||||
}
|
||||
|
||||
// ProxyRunGate reports whether a run may start under strict proxy mode.
|
||||
func (s *Scheduler) ProxyRunGate() (bool, string) {
|
||||
s.proxyMu.RLock()
|
||||
defer s.proxyMu.RUnlock()
|
||||
if !s.proxyEnabled || !s.proxyRequired {
|
||||
return true, ""
|
||||
}
|
||||
if s.proxyReady {
|
||||
return true, ""
|
||||
}
|
||||
reason := s.proxyBlockedReason
|
||||
if reason == "" {
|
||||
reason = "代理尚未就绪"
|
||||
}
|
||||
return false, reason
|
||||
}
|
||||
|
||||
func (s *Scheduler) stopRunChan() <-chan struct{} {
|
||||
s.runMu.Lock()
|
||||
defer s.runMu.Unlock()
|
||||
@@ -519,6 +543,10 @@ func (s *Scheduler) RunNow(accountProducts map[string]string) {
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次抢购不执行: %s", reason)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
deadline := start.Add(seckillMaxDuration)
|
||||
@@ -1194,6 +1222,10 @@ func (s *Scheduler) RunXiaodian(accountProducts map[string]string, attempts, del
|
||||
logger.LogEvent("代理", "error", "分组代理准备失败,本次和平小店抢购不执行: %v", err)
|
||||
return
|
||||
}
|
||||
if ok, reason := s.ProxyRunGate(); !ok {
|
||||
logger.LogEvent("代理", "error", "严格代理模式未就绪,本次和平小店抢购不执行: %s", reason)
|
||||
return
|
||||
}
|
||||
s.startXiaodianReport(accounts, products, reportSessionID)
|
||||
|
||||
stoppedAccounts := make(map[string]string)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package types
|
||||
|
||||
// ProxyStatusView is the structured proxy state exposed to the desktop and
|
||||
// remote dashboards. Proxy credentials must never be included.
|
||||
type ProxyStatusView struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Required bool `json:"required"`
|
||||
State string `json:"state"`
|
||||
ActiveCount int `json:"activeCount"`
|
||||
StandbyCount int `json:"standbyCount"`
|
||||
StandbyTarget int `json:"standbyTarget"`
|
||||
DirectCount int `json:"directCount"`
|
||||
LastError string `json:"lastError,omitempty"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
Groups []ProxyGroupStatus `json:"groups"`
|
||||
Accounts []AccountProxyView `json:"accounts"`
|
||||
}
|
||||
|
||||
// ProxyGroupStatus describes one active or standby proxy group.
|
||||
type ProxyGroupStatus struct {
|
||||
GroupIndex int `json:"groupIndex"`
|
||||
Role string `json:"role"`
|
||||
State string `json:"state"`
|
||||
AccountCount int `json:"accountCount"`
|
||||
Accounts []string `json:"accounts,omitempty"`
|
||||
Proxy string `json:"proxy,omitempty"`
|
||||
Region string `json:"region,omitempty"`
|
||||
RTTMs int64 `json:"rttMs,omitempty"`
|
||||
SwitchCount int `json:"switchCount"`
|
||||
LastError string `json:"lastError,omitempty"`
|
||||
}
|
||||
|
||||
// AccountProxyView maps one account to its current proxy group or direct route.
|
||||
type AccountProxyView struct {
|
||||
AccountName string `json:"accountName"`
|
||||
GroupIndex int `json:"groupIndex,omitempty"`
|
||||
GroupLabel string `json:"groupLabel"`
|
||||
Transport string `json:"transport"`
|
||||
Proxy string `json:"proxy,omitempty"`
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type SharedProxyConfig struct {
|
||||
// SharedProxySettings 使用指针区分“未提供”与显式零值,支持部分配置覆盖。
|
||||
type SharedProxySettings struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
Required *bool `json:"required,omitempty"`
|
||||
API *string `json:"api,omitempty"`
|
||||
AccountsPerProxy *int `json:"accountsPerProxy,omitempty"`
|
||||
SparePercent *int `json:"sparePercent,omitempty"`
|
||||
@@ -25,10 +26,11 @@ type SharedProxySettings struct {
|
||||
// SharedRemoteSettings 是本机或跨电脑共享的远端控制中心配置。
|
||||
// 令牌会写入共享 JSON 文件,调用方必须限制该文件权限并避免外部泄露。
|
||||
type SharedRemoteSettings struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Token *string `json:"token,omitempty"`
|
||||
MachineName *string `json:"machineName,omitempty"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
EnrollmentToken *string `json:"enrollmentToken,omitempty"`
|
||||
Token *string `json:"token,omitempty"`
|
||||
MachineName *string `json:"machineName,omitempty"`
|
||||
}
|
||||
|
||||
// FileDialogResult 返回通过系统文件选择器选中的路径。
|
||||
|
||||
@@ -18,20 +18,22 @@ type Config struct {
|
||||
SeckillMode SeckillMode `json:"seckillMode"` // 抢购模式:0=标准, 1=激进
|
||||
XiaodianPageSize int `json:"xiaodianPageSize"`
|
||||
ProxyEnabled bool `json:"proxyEnabled"` // 是否启用代理
|
||||
ProxyRequired bool `json:"proxyRequired"` // 严格代理模式:代理未就绪时不启动且不回退直连
|
||||
ProxyURL string `json:"proxyUrl"` // 代理地址,支持 http://, https://, socks5://
|
||||
ProxyAPI string `json:"proxyApi"` // 代理提取 API 地址,支持品赞与通用格式
|
||||
SharedProxyConfigFile string `json:"sharedProxyConfigFile"` // 本机保存的共享代理配置路径
|
||||
ProxyExpiresAt int64 `json:"proxyExpiresAt,omitempty"` // 当前静态代理的过期时间(Unix 毫秒),0 表示未知
|
||||
AutoFetchProxyOnSchedule bool `json:"autoFetchProxyOnSchedule"` // 定时抢购触发前自动从 API 提取最新代理
|
||||
AccountsPerProxy int `json:"accountsPerProxy"` // 每个独立代理承载的账号数
|
||||
ProxySparePercent int `json:"proxySparePercent"` // 额外提取的备用代理比例,至少预留一个
|
||||
ProxySparePercent int `json:"proxySparePercent"` // 额外提取的备用代理比例,最低和默认均为 50%
|
||||
ProxyAutoWhitelist bool `json:"proxyAutoWhitelist"` // 提取前自动添加本机公网 IP 白名单
|
||||
ProxyWhitelistReplace bool `json:"proxyWhitelistReplace"` // 白名单已满时替换最早 IP
|
||||
ProxyWhitelistPassword string `json:"proxyWhitelistPassword"` // 白名单签名使用的登录密码
|
||||
ProxyWhitelistSignKey string `json:"proxyWhitelistSignKey"` // 白名单签名使用的 AES 密钥
|
||||
RemoteEnabled bool `json:"remoteEnabled"` // 是否上报远端控制中心
|
||||
RemoteURL string `json:"remoteUrl"` // 远端控制中心根地址
|
||||
RemoteToken string `json:"remoteToken"` // 实例连接远端使用的令牌
|
||||
RemoteEnrollmentToken string `json:"remoteEnrollmentToken"` // 首次注册使用的控制中心注册令牌
|
||||
RemoteToken string `json:"remoteToken"` // 兼容旧版手工实例令牌,通常留空
|
||||
RemoteMachineName string `json:"remoteMachineName"` // 远端展示的机器名称,留空使用主机名
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user