fix: 修复 GeneratorExit 和 Task destroyed 警告
问题: 协程被取消/销毁时,finally 块中的异步操作触发 GeneratorExit 原因: GeneratorExit 是 BaseException 子类,不会被 Exception 捕获 修复内容: - server.py handle(): 捕获 CancelledError + GeneratorExit - server.py _tunnel(): 被取消时不执行 _record_stats() 异步操作 - instances.py _accept_connection(): 添加异常处理和 writer 关闭 - 所有取消场景都静默处理(不抛异常/不记录错误日志)
This commit is contained in:
+11
-4
@@ -104,6 +104,9 @@ class ConnectionHandler:
|
||||
log.debug("[%s] 超时", self.conn_id)
|
||||
except ConnectionError:
|
||||
log.debug("[%s] 连接错误", self.conn_id)
|
||||
except (asyncio.CancelledError, GeneratorExit):
|
||||
# 正常关闭,不记录错误
|
||||
pass
|
||||
except Exception as e:
|
||||
log.exception("[%s] 异常: %s", self.conn_id, e)
|
||||
finally:
|
||||
@@ -329,6 +332,7 @@ class ConnectionHandler:
|
||||
async def _tunnel(self, dst_reader, dst_writer):
|
||||
"""双向隧道转发。"""
|
||||
f1 = f2 = None
|
||||
cancelled = False
|
||||
try:
|
||||
# 获取限速参数
|
||||
user = None
|
||||
@@ -349,7 +353,9 @@ class ConnectionHandler:
|
||||
await asyncio.gather(f1, f2, return_exceptions=True)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
cancelled = True
|
||||
except GeneratorExit:
|
||||
cancelled = True
|
||||
except Exception as e:
|
||||
log.exception("[%s] 隧道异常: %s", self.conn_id, e)
|
||||
finally:
|
||||
@@ -359,11 +365,12 @@ class ConnectionHandler:
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
except (asyncio.CancelledError, GeneratorExit):
|
||||
pass
|
||||
self._close_streams(dst_reader, dst_writer)
|
||||
# 记录最终统计
|
||||
await self._record_stats()
|
||||
# 记录最终统计 - 协程被取消时不做异步操作(避免 GeneratorExit)
|
||||
if not cancelled:
|
||||
await self._record_stats()
|
||||
|
||||
async def _forward(self, src, dst, direction, speed_limit_mbps, user):
|
||||
"""单向转发,带限速。"""
|
||||
|
||||
Reference in New Issue
Block a user