Skip to content

Fix runtime port fallback on reserved Windows ports - #48

Closed
yukinoshi wants to merge 1 commit into
shengjidaguai-china:mainfrom
yukinoshi:fix/runtime-port-fallback
Closed

yukinoshi wants to merge 1 commit into
shengjidaguai-china:mainfrom
yukinoshi:fix/runtime-port-fallback

Conversation

@yukinoshi

Copy link
Copy Markdown
Member

Summary

Fixes #47

Windows 重启后 winnat(Hyper-V/WSL/Docker 依赖)会随机保留若干段 TCP 端口,当默认 proxy_port: 3456 落入保留段时,cdp-proxy bind 失败退出,Browser Runtime 永远无法启动(详见 Issue)。本 PR 扩展 ensure_runtime() 的端口回退条件,使「端口无响应且无法 bind」的场景也能自动换到可用端口,复用现有回退机制,改动最小化。

问题回顾

ensure_runtime() 原有的端口回退只在「端口被其他 HTTP 服务占用」(health 返回非 bosshunter 标识)时触发:

health = runtime_health(browser)
if health and health.get("runtime") != "bosshunter":   # 保留段场景 health 为 None → 回退被跳过
    ...
start_runtime(...)   # 继续在绑不上的端口启动 → 代理退出 → 轮询超时 → False

端口被系统保留时:无进程监听 → health 为 None;bind 报 EACCES。两个信号原代码都没有利用。

改动内容

1. src/bosshunter/browser/runtime/__init__.py — ensure_runtime()

回退条件从单一场景扩展为两种:

needs_fallback = (health is not None and health.get("runtime") != "bosshunter") or (
    health is None and not _is_port_available(host, port)   # 新增:端口无响应且 bind 不上
)

复用现有的 _find_available_runtime_port()(bind 探测扫描 proxy_port+1 起 100 个端口,被保留的端口会自动跳过)和 _switch_runtime_port()(已同时更新进程级配置,Web 控制台与 CLI 的所有浏览器操作都经由此处,无需其他改动)。

2. 同文件 — _is_port_available()

移除 SO_REUSEADDR:Windows 上该选项允许绑定已被其他进程监听的端口,会使探测误报「端口可用」。移除后顺带让「端口被静默非 HTTP 服务占用」的场景也能正确触发回退。

3. tests/test_browser_runtime.py

新增 test_ensure_runtime_uses_next_free_port_when_default_is_system_reserved:mock「配置端口无响应 + bind 失败」,断言自动切换到 3457、config 被更新、代理以新端口启动(写法对齐既有的 non_bosshunter_service 用例)。

设计决策

  • 不把回退选中的端口持久化到 config.yaml:保留段每次重启都变,持久化反而会固化到一个未来可能失效的端口;逐次探测自愈更稳。
  • 不改 cdp-proxy.mjs:端口由 Python 侧统一编排,通过 BOSSHUNTER_BROWSER_PROXY_PORT 环境变量传入,Node 侧无需感知回退逻辑。

测试与验证

  • 单元测试:tests/test_browser_runtime.py + tests/test_browser_diagnostics.py 共 24 个全部通过(含新增用例)
  • 真实场景复现验证:将 config.yaml 的 proxy_port 临时设为 3456(当前系统保留段 3414-3513 内)→ bosshunter connect 自动回退到 3514,四项检测全绿:
✓ Node.js 可用: v22.22.2
✓ BossHunter CDP Runtime 已启动: http://127.0.0.1:3514
✓ 已连接 Chrome
✓ 发现 BOSS直聘 页面: 「深圳招聘网」海量深圳人才招聘信息 - BOSS直聘
  • 正常路径回归:proxy_port: 8456(可绑定)→ 直接启动,无行为变化
  • bosshunter --help 正常运行
  • ruff:改动行无新增告警(该文件存在 4 处历史告警,未触碰)

@powerycy

Copy link
Copy Markdown
Collaborator

该 Windows 保留端口回退修复已完整纳入 PR #62,并与多平台及监测风控代码完成全量回归。此 PR 由 #62 取代,感谢贡献,现关闭。

@powerycy

Copy link
Copy Markdown
Collaborator

最终状态:Windows 系统保留端口自动回退已通过 #62 合并到 main;对应 Issue #47 的作者本机也已确认通过。最终整合回归 401 项、16 个子测试通过,Python 3.11 / 3.12 CI 通过。贡献已列入 #74。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 端口报错连接不上

2 participants