修复问题: - 添加缺失的 httpx 依赖到 requirements.txt - 修复前端批量删除参数格式与后端不匹配(数组->对象数组) - 移除 app/api/main.py 中重复创建 app 的冗余代码 - 修复 Plugins.vue v-model 直接修改 store 状态的 Vue 警告 - 修复 README 端口/启动命令文档与实际配置不一致 - 修正 pytest.ini 过时配置 (asyncio_default_fixture_loop_scope) - 修复 WebUI index.html 语言设置为 zh-CN - 修复 .gitignore 错误忽略 tests/ 目录 后端优化: - 修复调度器默认间隔从 5 秒改为 30 分钟,避免无节制验证 - 修复 validate_all_now 在调度器停止时无法执行的 bug - 设置保存后热更新运行中调度器的验证间隔 - 将 update_score 优化为原子单事务 SQL,消除并发竞态 - 导出功能改为真正的流式分批读取(iter_batches),降低大导出内存占用 - ProxyResponse Schema 补齐 response_time_ms 字段 - 日志级别改为从配置动态读取,不再硬编码 INFO - 清理 validator_service 中的冗余 try/finally 代码 插件健壮性: - 修复 ip3366/ip89/kuaidaili/proxylist_download/speedx/yundaili/proxyscrape 的端口范围检查和 IPv6 地址解析问题(改用 rsplit + 1-65535 校验) - 修复 PluginService.list_plugins 并发竞争条件 - 修复 run_all_plugins 去重逻辑与数据库 UNIQUE 约束保持一致 - 修复 proxyscrape 异常时错误跳过 fallback 的 bug 测试: - 新增 7 个插件解析单元测试 - 新增 update_score 自动删除和 iter_batches 流式读取测试 - 全部 74 个测试通过
110 lines
4.1 KiB
Python
110 lines
4.1 KiB
Python
"""代理验证服务 - 支持 HTTP/HTTPS/SOCKS4/SOCKS5"""
|
|
import asyncio
|
|
import random
|
|
import time
|
|
import aiohttp
|
|
import aiohttp_socks
|
|
from typing import Tuple
|
|
from app.core.log import logger
|
|
|
|
|
|
class ValidatorService:
|
|
"""代理验证器"""
|
|
|
|
# 测试 URL
|
|
TEST_URLS = {
|
|
"http": ["http://httpbin.org/ip", "http://api.ipify.org"],
|
|
"https": ["https://httpbin.org/ip", "https://api.ipify.org"],
|
|
}
|
|
|
|
def __init__(
|
|
self,
|
|
timeout: float = 5.0,
|
|
connect_timeout: float = 3.0,
|
|
max_concurrency: int = 50,
|
|
):
|
|
self.timeout = timeout
|
|
self.connect_timeout = connect_timeout
|
|
self.max_concurrency = max_concurrency
|
|
self.semaphore = asyncio.Semaphore(max_concurrency)
|
|
|
|
# 共享 HTTP/HTTPS ClientSession
|
|
self._http_connector = aiohttp.TCPConnector(
|
|
ssl=False,
|
|
limit=max_concurrency,
|
|
limit_per_host=max_concurrency,
|
|
force_close=False,
|
|
)
|
|
self._timeout = aiohttp.ClientTimeout(
|
|
total=timeout, connect=connect_timeout
|
|
)
|
|
self._http_session = aiohttp.ClientSession(
|
|
connector=self._http_connector,
|
|
timeout=self._timeout,
|
|
)
|
|
|
|
def _get_test_url(self, protocol: str) -> str:
|
|
"""获取测试 URL"""
|
|
urls = self.TEST_URLS.get(protocol.lower(), self.TEST_URLS["http"])
|
|
return random.choice(urls)
|
|
|
|
async def validate(self, ip: str, port: int, protocol: str = "http") -> Tuple[bool, float]:
|
|
"""验证单个代理,返回 (是否有效, 延迟毫秒)"""
|
|
protocol = protocol.lower()
|
|
|
|
async with self.semaphore:
|
|
start = time.time()
|
|
try:
|
|
if protocol in ("socks4", "socks5"):
|
|
return await self._validate_socks(ip, port, protocol, start)
|
|
else:
|
|
return await self._validate_http(ip, port, protocol, start)
|
|
except asyncio.TimeoutError:
|
|
logger.debug(f"Validation timeout: {ip}:{port} ({protocol})")
|
|
return False, 0.0
|
|
except Exception as e:
|
|
logger.debug(f"Validation error {ip}:{port} ({protocol}): {e}")
|
|
return False, 0.0
|
|
|
|
async def _validate_http(self, ip: str, port: int, protocol: str, start: float) -> Tuple[bool, float]:
|
|
"""验证 HTTP/HTTPS 代理"""
|
|
proxy_url = f"http://{ip}:{port}"
|
|
test_url = self._get_test_url(protocol)
|
|
|
|
async with self._http_session.get(test_url, proxy=proxy_url, allow_redirects=True) as response:
|
|
if response.status in (200, 301, 302):
|
|
latency = round((time.time() - start) * 1000, 2)
|
|
logger.info(f"HTTP valid: {ip}:{port} ({protocol}) {latency}ms")
|
|
return True, latency
|
|
return False, 0.0
|
|
|
|
async def _validate_socks(self, ip: str, port: int, protocol: str, start: float) -> Tuple[bool, float]:
|
|
"""验证 SOCKS4/SOCKS5 代理"""
|
|
proxy_type = (
|
|
aiohttp_socks.ProxyType.SOCKS4
|
|
if protocol == "socks4"
|
|
else aiohttp_socks.ProxyType.SOCKS5
|
|
)
|
|
connector = aiohttp_socks.ProxyConnector(
|
|
proxy_type=proxy_type,
|
|
host=ip,
|
|
port=port,
|
|
rdns=True,
|
|
ssl=False,
|
|
)
|
|
timeout = aiohttp.ClientTimeout(total=self.timeout, connect=self.connect_timeout)
|
|
test_url = self._get_test_url("http")
|
|
|
|
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
|
|
async with session.get(test_url, allow_redirects=True) as response:
|
|
if response.status in (200, 301, 302):
|
|
latency = round((time.time() - start) * 1000, 2)
|
|
logger.info(f"SOCKS valid: {ip}:{port} ({protocol}) {latency}ms")
|
|
return True, latency
|
|
return False, 0.0
|
|
|
|
async def close(self):
|
|
"""关闭共享的 HTTP ClientSession"""
|
|
if self._http_session and not self._http_session.closed:
|
|
await self._http_session.close()
|