Repository navigation
fix: 修复反向 WebSocket 重连时的重复连接 - #144
Merged
Merged
Conversation
v11 反向 WS 的 reconnect() 在 await close() 之后才检查连接任务,且无条件覆盖 self.ws。new_event() 对每条事件一个 task 并发调用 push_event,断线瞬间的并发 reconnect 会在 close 卡住时各自建连,留下孤儿连接。改为 asyncio.Lock 串行重连,拿到锁后若已就绪则复用,先关旧连接再建新连接。 on_ready 没有幂等保护:discord.py 在 RESUME 失败重新 IDENTIFY 后会再次派发 READY,init_connections() 只 append 不清理,导致每条反向 WS 配置再建一整套客户端(旧连接继续推事件)。加入模块级初始化标记,连接创建开始后不再重复初始化。 新增回归测试:并发 reconnect 只保留一条连接、on_ready 只初始化一次。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
问题
反向 WebSocket 在重连时仍可能重复建立连接,两个独立来源:
reconnect()并发无互斥:connect_task在await self.ws.close()之后才检查,且self.ws = None无条件覆盖。new_event()对每条事件一个 task 调用push_event,断线瞬间会产生一批并发 reconnect;只要某个close()卡住(close_timeout / 事件循环繁忙),等待者会在前一个 connect 完成后各自建连,把上一代连接变成孤儿。本地 fuzz(8 个并发 reconnect + close 抖动)修复前 20/20 次试验出现多连接(最多 8 条),修复后 0/20。on_ready重复触发:discord.py 在 RESUME 失败重新 IDENTIFY 后会再次派发 READY。on_ready没有幂等保护,init_connections()只往全局列表 append、不清理也不关闭旧连接,导致每条反向 WS 配置再建一整套客户端(旧连接继续推事件)。本地实测 server 侧连接数 2 → 4。改动
network/v11/ws_reverse.pyreconnect()用asyncio.Lock串行化;拿到锁后若is_ready()直接复用,先关闭旧连接再建立新连接connect_task,初始化统一走reconnect()is_ready()显式处理ws is Noneutils/event/discord_event.pyon_ready加模块级初始化标记(放在tree.sync之后、init_connections之前),重复触发时不再重复初始化测试
tests/test_ws_reverse_reconnect.py:单次重连保持 1 条连接;4 个并发 reconnect(close 抖动)后 server 侧仍只有 1 条连接tests/test_on_ready_once.py:连续触发 3 次on_ready,init_connections/init_database只执行一次poetry run pytest:45 passed(原 42 + 新增 3);在修复前代码上这两个回归测试会失败备注
V12 反向 WS 使用另一套
reconnect_task机制,本次未改动。