kikl Claude Code commited on
Commit
75c2b7c
·
1 Parent(s): 428fc0c

Patch khl.py websocket receiver to retry instead of dying

Browse files

khl/receiver.py 的 start() 里,_get_gateway() 失败后会提前 return,
_RAW_GATEWAY 保持空串,紧随其后的 ws_connect() 抛异常——该异常在 while
循环之外、也没人 catch,会一路冒到 bot.start(),接收循环彻底终止且永不重试。
症状是进程活着、/health 正常,但机器人收不到任何消息,只能重启恢复。

补丁:
- 捕获异常并指数退避重试(2s 起,上限 60s)
- 旁路记录 HELLO / RECONNECT / RESUME ACK 信令,
便于区分「被服务端拒绝」和「连上了但收不到消息」两种情况

Co-Authored-By: Claude Code <noreply@anthropic.com>

Files changed (2) hide show
  1. app.py +5 -0
  2. utils/khl_patch.py +98 -0
app.py CHANGED
@@ -15,6 +15,11 @@ from utils import permission, timeutil
15
  from utils.money import parse_amount, fmt
16
  from utils.rate_limiter import rate_limiter
17
  from utils.card_builder import BTN_CHECKIN, BTN_CHECKOUT
 
 
 
 
 
18
 
19
  bot = Bot(token=BOT_TOKEN)
20
  _start_time = time.monotonic()
 
15
  from utils.money import parse_amount, fmt
16
  from utils.rate_limiter import rate_limiter
17
  from utils.card_builder import BTN_CHECKIN, BTN_CHECKOUT
18
+ from utils import khl_patch
19
+
20
+ # 必须在 bot.start() 之前打——khl.py 的 websocket 接收循环遇到异常会静默死掉,
21
+ # 打完补丁才会退避重试,且连接生命周期会记进日志。
22
+ khl_patch.apply()
23
 
24
  bot = Bot(token=BOT_TOKEN)
25
  _start_time = time.monotonic()
utils/khl_patch.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """给 khl.py 打补丁:让 websocket 接收循环在异常后能重试,而不是静默死掉。
2
+
3
+ 原实现(khl/receiver.py):
4
+
5
+ async def start(self):
6
+ async with ClientSession(loop=self.loop) as cs:
7
+ while True:
8
+ await self._get_gateway(cs)
9
+ await self._connect_gateway_and_handle_msg(cs)
10
+
11
+ 问题:`_get_gateway()` 在 `res_json['code'] != 0` 时提前 return,此时
12
+ `_RAW_GATEWAY` 仍是空串(或上一次的旧值)。紧接着 `_connect_gateway_and_handle_msg`
13
+ 里的 `cs.ws_connect()` 会抛异常 —— 而这个异常:
14
+
15
+ - 在 `while True` 之外,绕过了内层 `try`
16
+ - 也没人 catch,会一路冒到 client.start() -> bot.start()
17
+ - 结果就是接收循环彻底终止,**永不重试**,只有重启进程才能恢复
18
+
19
+ 网络抖一下、网关接口限流一次、容器刚起来 DNS 还没就绪,都会触发。表现为
20
+ 「进程还活着(HTTP /health 正常),但机器人收不到任何消息」。
21
+
22
+ 补丁做两件事:
23
+ 1. 捕获异常 + 指数退避重试,让接收循环不会死
24
+ 2. 补上连接生命周期日志(HELLO / RECONNECT 信令等),
25
+ 这样「连上了但收不到消息」时能直接看出是服务端拒绝还是路由问题
26
+ """
27
+ import asyncio
28
+ import logging
29
+ import zlib
30
+
31
+ from aiohttp import ClientSession
32
+ from khl.receiver import WebsocketReceiver
33
+
34
+ log = logging.getLogger("KhlPatch")
35
+
36
+ _orig_handle_raw = WebsocketReceiver._handle_raw
37
+
38
+
39
+ async def _patched_start(self):
40
+ """替换 WebsocketReceiver.start,异常不再杀死接收循环。"""
41
+ async with ClientSession(loop=self.loop) as cs:
42
+ backoff = 2
43
+ while True:
44
+ try:
45
+ await self._get_gateway(cs)
46
+ if not self._RAW_GATEWAY:
47
+ raise RuntimeError("获取 gateway 失败,地址为空")
48
+ log.info("[receiver] gateway 已获取,正在建立 websocket")
49
+ backoff = 2 # 连上了就重置退避
50
+ await self._connect_gateway_and_handle_msg(cs)
51
+ # 正常返回说明连接断了(内层 try 已捕获并记录)
52
+ log.warning("[receiver] websocket 连接已结束,准备重连")
53
+ except asyncio.CancelledError:
54
+ raise
55
+ except Exception as e:
56
+ log.warning("[receiver] 连接异常: %r;%s 秒后重试", e, backoff)
57
+ await asyncio.sleep(backoff)
58
+ backoff = min(backoff * 2, 60)
59
+ continue
60
+ await asyncio.sleep(2)
61
+
62
+
63
+ async def _patched_handle_raw(self, raw):
64
+ """在原始处理前先看一眼信令,把 khl.py 默认静默丢弃的信息记下来。
65
+
66
+ s=1 HELLO 连接握手结果,code != 0 就是被服务端拒了
67
+ s=3 PONG 心跳回应
68
+ s=5 RECONNECT 服务端要求重连(当前连接已失效)
69
+ s=6 RESUME ACK resume 成功,离线消息已补齐
70
+ """
71
+ try:
72
+ data = raw.data
73
+ data = zlib.decompress(data) if self.compress else data
74
+ pkg = self._cert.decode_raw(data)
75
+ s = pkg.get("s")
76
+ if s == 1:
77
+ log.info("[receiver] HELLO: %s", pkg.get("d"))
78
+ elif s == 5:
79
+ log.warning("[receiver] 服务端要求 RECONNECT: %s", pkg.get("d"))
80
+ elif s == 6:
81
+ log.info("[receiver] RESUME ACK: %s", pkg.get("d"))
82
+ except Exception:
83
+ pass # 解析失败就交给原实现去报错,这里只做旁路观察
84
+ return await _orig_handle_raw(self, raw)
85
+
86
+
87
+ _applied = False
88
+
89
+
90
+ def apply():
91
+ """必须在 bot.start() 之前调用。"""
92
+ global _applied
93
+ if _applied:
94
+ return
95
+ WebsocketReceiver.start = _patched_start
96
+ WebsocketReceiver._handle_raw = _patched_handle_raw
97
+ _applied = True
98
+ log.info("[KhlPatch] 已应用 websocket 重连补丁")