Peach: Local-first video metadata scraper and media manager.
fix(metadata): 自定义来源共用查询时间预算
longmeidaob9332586137e
diff --git a/docs/CUSTOM_SOURCES.md b/docs/CUSTOM_SOURCES.mdindex b61c1b310..f8cb5c817 100644--- a/docs/CUSTOM_SOURCES.md+++ b/docs/CUSTOM_SOURCES.md@@ -38,7 +38,9 @@ Peach 已内置一本道适配器,此例用于说明接口配置,不需要## 网络与存储接口使用 HTTPS 公网域名、默认 443 端口,拒绝用户信息、片段、私网解析结果和重定向。-请求最多 15 秒、响应最多 1 MiB。直连或 Peach 代理都通过 cURL `CONNECT_TO` 固定已验证的+查询使用最多 15 秒的时间预算,响应最多 1 MiB;代理配置、DNS 解析和会话准备共用该预算。+系统 DNS 解析为同步调用,无法在预算到期时强制取消;解析返回时若预算已耗尽,不再发起+HTTP 请求,因此实际返回时间可能超过预算。直连或 Peach 代理都通过 cURL `CONNECT_TO` 固定已验证的公共 IP,TLS 的 SNI 和证书验证仍使用接口原域名。Peach 代理沿用已保存的连接设置,不另存凭据。配置位于本机 `secrets/custom-metadata.json`,通过文件锁和原子替换保存;不写 ledger。diff --git a/src/peach/custom_metadata.py b/src/peach/custom_metadata.pyindex 46a3847ac..71337f7ca 100644--- a/src/peach/custom_metadata.py+++ b/src/peach/custom_metadata.py@@ -149,9 +149,19 @@ def parse(config: dict, code: str, document: object) -> SiteRecord:tags=strings('tags') if 'tags' in values else None, confidence=0.5)+def _remaining_seconds(deadline: float) -> float:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise ValueError('来源查询已超时')+ return remaining++def fetch_json(url: str, timeout: float, *, client_options=None):+ expires = time.monotonic() + timeout+ _remaining_seconds(expires)host = urlsplit(url).hostname or ''addresses = host_addresses(host)+ _remaining_seconds(expires)if not addresses or any(not ipaddress.ip_address(ip).is_global for ip in addresses):raise ValueError('来源域名必须解析到公网地址')address = addresses[0]@@ -166,7 +176,7 @@ def fetch_json(url: str, timeout: float, *, client_options=None):curl_options[CurlOpt.NOPROXY] = '*'with requests.Session(curl_options=curl_options, **options) as client:try:- with client.stream('GET', url, timeout=timeout, allow_redirects=False,+ with client.stream('GET', url, timeout=_remaining_seconds(expires), allow_redirects=False,headers={'Accept': 'application/json'}) as response:if response.status_code != 200:raise ValueError(f'来源响应 HTTP {response.status_code}')@@ -184,9 +194,10 @@ def fetch_json(url: str, timeout: float, *, client_options=None):def query(config: dict, code: str, *, deadline=None, secrets_root=None) -> SiteRecord:checked = validate(config)code = validate_provider_code(code)- timeout = min(15.0, deadline - time.monotonic()) if deadline else 15.0- if timeout <= 0:- raise ValueError('来源查询已超时')+ expires = time.monotonic() + 15.0+ if deadline is not None:+ expires = min(expires, deadline)+ _remaining_seconds(expires)url = endpoint(checked, code)options = Noneif checked['network'] == 'peach_proxy':@@ -195,7 +206,7 @@ def query(config: dict, code: str, *, deadline=None, secrets_root=None) -> SiteRfrom .peach_proxy import client_optionsoptions = client_options(Path(secrets_root))try:- document = fetch_json(url, timeout, client_options=options)+ document = fetch_json(url, _remaining_seconds(expires), client_options=options)except (json.JSONDecodeError, UnicodeError) as error:raise ValueError('来源响应不是有效 JSON') from errorreturn parse(config, code, document)diff --git a/tests/test_custom_metadata.py b/tests/test_custom_metadata.pyindex 36557209f..025d2c472 100644--- a/tests/test_custom_metadata.py+++ b/tests/test_custom_metadata.py@@ -4,7 +4,7 @@ import timeimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import Mock, patch+from unittest.mock import MagicMock, Mock, patchfrom peach import custom_metadata as customfrom peach.library_processing import _RemoteSession@@ -53,6 +53,49 @@ class CustomMetadataTests(unittest.TestCase):custom.fetch_json('https://metadata.example.com/ABW-001', 2)session.assert_not_called()+ def test_http_uses_the_budget_left_by_proxy_dns_and_session_preparation(self):+ clock = [100.0]+ response = Mock(status_code=200)+ response.iter_content.return_value = [b'{"data":{"id":"ABW-001","title":"example","cast":[]}}']+ session = MagicMock()+ client = session.__enter__.return_value+ client.stream.return_value.__enter__.return_value = response+ def proxy_options(_root):+ clock[0] += 2+ return {'proxy': 'http://127.0.0.1:7890', 'trust_env': False}+ def addresses(_host):+ clock[0] += 6+ return ('1.1.1.1',)+ def prepare_session(**_options):+ clock[0] += 1+ return session+ with patch.object(custom.time, 'monotonic', side_effect=lambda: clock[0]), \+ patch('peach.peach_proxy.client_options', side_effect=proxy_options), \+ patch.object(custom, 'host_addresses', side_effect=addresses), \+ patch.object(custom.requests, 'Session', side_effect=prepare_session):+ record = custom.query(definition(network='peach_proxy'), 'ABW-001', secrets_root=Path('.'))+ self.assertEqual(record.title, 'example')+ self.assertEqual(client.stream.call_args.kwargs['timeout'], 6)++ def test_exhausted_dns_budget_does_not_start_http(self):+ def exercise(dns_elapsed):+ clock = [100.0]+ response = Mock(status_code=200)+ response.iter_content.return_value = [b'{"ok":true}']+ def addresses(_host):+ clock[0] += dns_elapsed+ return ('1.1.1.1',)+ with patch.object(custom.time, 'monotonic', side_effect=lambda: clock[0]), \+ patch.object(custom, 'host_addresses', side_effect=addresses), \+ patch.object(custom.requests, 'Session') as session:+ session.return_value.__enter__.return_value.stream.return_value.__enter__.return_value = response+ with self.assertRaisesRegex(ValueError, '超时'):+ custom.fetch_json('https://metadata.example.com/ABW-001', 15)+ session.assert_not_called()+ for dns_elapsed in (15, 16):+ with self.subTest(dns_elapsed=dns_elapsed):+ exercise(dns_elapsed)+def test_formal_pipeline_consumes_enabled_source_after_builtin_chain(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp).resolve()