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:
Your Name
2026-07-17 00:06:01 +08:00
parent 5c1f0122a2
commit ae8334140d
2 changed files with 28 additions and 12 deletions
+17 -8
View File
@@ -114,14 +114,23 @@ class Socks5Server:
)
async def _accept_connection(self, reader, writer):
with self._lock:
self._active_connections += 1
handler = ConnectionHandler(
reader, writer, self.config, self.user_service,
flask_app=self.flask_app,
on_close_cb=self._on_connection_close
)
await handler.handle()
try:
with self._lock:
self._active_connections += 1
handler = ConnectionHandler(
reader, writer, self.config, self.user_service,
flask_app=self.flask_app,
on_close_cb=self._on_connection_close
)
await handler.handle()
except (asyncio.CancelledError, GeneratorExit):
# 服务器关闭时正常取消,不记录错误
pass
finally:
try:
writer.close()
except Exception:
pass
def _on_connection_close(self, handler):
with self._lock: