修复所有资源泄漏问题(P0级bug)

修复的Bug:
- Bug #21: Playwright浏览器实例泄漏
- Bug #22: 数据库连接泄漏(已由连接池解决)
- Bug #23: 截图文件句柄泄漏
- Bug #24: 线程资源未清理
- Bug #25: requests.Session对象泄漏

主要改进:
1. PlaywrightAutomation类:
   - 添加atexit注册,确保进程退出时关闭浏览器
   - 添加__enter__/__exit__支持context manager
   - 添加_closed标志防止重复关闭
   - 添加_cleanup_on_exit静默清理方法

2. APIBrowser类:
   - 添加atexit注册,确保Session正确关闭
   - 添加__enter__/__exit__支持context manager
   - 添加_closed标志防止重复关闭

3. 截图功能增强:
   - 使用临时文件机制
   - 添加文件大小验证
   - 失败时自动清理临时文件
   - 确保不产生垃圾文件

4. 应用关闭清理:
   - 添加cleanup_on_exit()函数
   - 注册SIGINT/SIGTERM信号处理器
   - 停止所有运行中的任务
   - 等待线程优雅退出
   - 关闭浏览器线程池
   - 关闭数据库连接池

影响:
- 防止长期运行导致的内存泄漏
- 确保进程异常退出时正确清理资源
- 提升系统稳定性和可靠性

受影响文件:
- playwright_automation.py
- api_browser.py
- app.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-11 13:48:06 +08:00
parent 795ff7f1a7
commit 114a4107bb
3 changed files with 156 additions and 2 deletions

View File

@@ -9,6 +9,7 @@ import requests
from bs4 import BeautifulSoup
import re
import time
import atexit
from typing import Optional, Callable
from dataclasses import dataclass
@@ -38,6 +39,8 @@ class APIBrowser:
self.logged_in = False
self.log_callback = log_callback
self.stop_flag = False
self._closed = False # 防止重复关闭
# 设置代理
if proxy_config and proxy_config.get("server"):
proxy_server = proxy_config["server"]
@@ -49,6 +52,9 @@ class APIBrowser:
else:
self.proxy_server = None
# 注册退出清理函数
atexit.register(self._cleanup_on_exit)
def log(self, message: str):
"""记录日志"""
if self.log_callback:
@@ -382,7 +388,29 @@ class APIBrowser:
def close(self):
"""关闭会话"""
if self._closed:
return
self._closed = True
try:
self.session.close()
except:
pass
def _cleanup_on_exit(self):
"""进程退出时的清理函数由atexit调用"""
if not self._closed:
try:
self.session.close()
self._closed = True
except:
pass
def __enter__(self):
"""Context manager支持 - 进入"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager支持 - 退出"""
self.close()
return False # 不抑制异常