Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(covers): 隔离单来源冷却并保留整趟停止信号

longmeidaob0f73c4ab4c7
diff --git a/src/peach/jav_cover_fetch.py b/src/peach/jav_cover_fetch.py
index 91a4df6f9..fa4463bfe 100644
--- a/src/peach/jav_cover_fetch.py
+++ b/src/peach/jav_cover_fetch.py
@@ -57,7 +57,7 @@ from peach.scripting import USER_AGENT, open_readonly
from peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIR
from peach.http import HttpRequest, HttpTransport, HttpxTransport
from peach.scripting import HostLimiter
-from peach.scraping_access import SOURCES, SourcePaused, SourceTransport, source_for
+from peach.scraping_access import SOURCES, SourceBudgetExhausted, SourcePaused, SourceTransport, source_for
from peach.config import SECRETS_DIR
from peach.jobs import DiskGuard, JobPolicyError
from peach.task_runs import TaskRunHandle, cli_run, inert_handle
@@ -725,11 +725,26 @@ def prestige_images(transport: HttpTransport, code: str, *,
return []
+def _source_query(query, *, empty, record):
+ """单个来源冷却只记为未作答;本趟预算耗尽继续交给任务停止。"""
+ try:
+ return query()
+ except SourceBudgetExhausted:
+ raise
+ except SourcePaused:
+ record('source_unanswered')
+ record('paused')
+ return empty()
+
+
def prestige_group_images(transport: HttpTransport, code: str, *,
- deadline: float | None = None) -> list[Candidate]:
+ deadline: float | None = None, record=lambda key: None) -> list[Candidate]:
"""汇总 Prestige 与 MGS 的官方候选,尺寸由统一探测比较。"""
- official = prestige_images(transport, code, deadline=deadline)
- return _unique_candidates(official + mgstage_images(transport, code, deadline=deadline))
+ official = _source_query(lambda: prestige_images(transport, code, deadline=deadline),
+ empty=list, record=record)
+ mgs = _source_query(lambda: mgstage_images(transport, code, deadline=deadline),
+ empty=list, record=record)
+ return _unique_candidates(official + mgs)
def probe_size(transport: HttpTransport, candidate: Candidate, *,
@@ -776,31 +791,42 @@ def _site_candidates(transport: HttpTransport, code: str, evidence: MetadataEvid
prestige = _is_prestige(evidence) or 'prestige' in maker_sites(code)
amateur = is_amateur_code(code) or 'mgstage' in evidence.sources
if prestige:
- candidates += prestige_group_images(transport, code, deadline=deadline)
+ candidates += prestige_group_images(transport, code, deadline=deadline, record=record)
elif amateur:
- candidates += mgstage_images(transport, code, deadline=deadline)
+ candidates += _source_query(lambda: mgstage_images(transport, code, deadline=deadline),
+ empty=list, record=record)
if candidates or ((prestige or amateur) and evidence.candidates):
return candidates
if ('dmm' not in evidence.sources
and not prestige and not amateur and not is_uncensored_code(code)):
try:
- live_evidence = dmm_evidence(transport, code, deadline=deadline)
+ live_evidence = _source_query(lambda: dmm_evidence(transport, code, deadline=deadline),
+ empty=MetadataEvidence, record=record)
candidates += list(live_evidence.candidates)
- except (Unavailable, SourcePaused, httpx.TransportError):
+ except (Unavailable, httpx.TransportError):
record('source_unanswered')
# 有成功快照时不重复打 r18;失败快照不算证据,仍允许联网刷新。
if ('r18dev' not in evidence.sources and not live_evidence.candidates
and not ('dmm' in evidence.sources and evidence.candidates)):
- live_evidence = r18_evidence(transport, code, deadline=deadline, record=record)
+ live_evidence = _source_query(
+ lambda: r18_evidence(transport, code, deadline=deadline, record=record),
+ empty=MetadataEvidence, record=record)
candidates += list(live_evidence.candidates)
_sleep_within(delay, deadline)
# 目录新识别出 Prestige 时补问集团自营渠道。
if not prestige and _is_prestige(live_evidence):
- candidates += prestige_group_images(transport, code, deadline=deadline)
+ candidates += prestige_group_images(transport, code, deadline=deadline, record=record)
_sleep_within(delay, deadline)
return candidates
+def _unanswered_error(diagnostics: dict, message: str) -> Exception:
+ unanswered = sum(diagnostics.get(key, 0) for key in ('source_unanswered', 'unanswered', 'download_failed'))
+ if unanswered and diagnostics.get('paused', 0) == unanswered:
+ return SourcePaused('封面来源正在冷却,请稍后重试;已有图片保留')
+ return Unavailable(message)
+
+
def best_cover(transport: HttpTransport, code: str, delay: float, *,
metadata_root: Path | None = None,
prior_candidates: tuple[Candidate, ...] = (),
@@ -836,7 +862,7 @@ def best_cover(transport: HttpTransport, code: str, delay: float, *,
def source_transport(request, timeout, limit):
try:
response = transport(request, timeout, limit)
- except (httpx.TransportError, SourcePaused):
+ except httpx.TransportError:
record('source_unanswered')
raise
if response.status not in (200, 206, 404):
@@ -851,22 +877,24 @@ def best_cover(transport: HttpTransport, code: str, delay: float, *,
deadline=deadline, record=record)])
if not asked:
if diagnostics.get('source_unanswered'):
- raise Unavailable('官方目录查询未完成,尚未取得封面候选')
+ raise _unanswered_error(diagnostics, '官方目录查询未完成,尚未取得封面候选')
raise NotFound("所有渠道都没有候选")
measured = _measure(transport, asked, record, minimum_width=minimum_width,
delay=delay, deadline=deadline)
if not measured:
# 每张候选都回过话(404、太小、占位图、解不开)就是来源的确定答复,下次再问还是这几张:
# 交 `NotFound`,采集任务记下一周不问。有一张断在连接、5xx 或拒绝访问上才可能是这趟没问成。
- kind = Unavailable if diagnostics.get("unanswered") or diagnostics.get('source_unanswered') else NotFound
- raise kind(_no_usable_official(diagnostics))
+ if diagnostics.get("unanswered") or diagnostics.get('source_unanswered'):
+ raise _unanswered_error(diagnostics, _no_usable_official(diagnostics))
+ raise NotFound(_no_usable_official(diagnostics))
try:
return _download_best(transport, measured, record, minimum_width=minimum_width,
minimum_quality=minimum_quality, minimum_pixels=minimum_pixels,
deadline=deadline)
- except NotFound as error:
- if diagnostics.get('source_unanswered') or diagnostics.get('unanswered'):
- raise Unavailable(str(error)) from error
+ except Unavailable as error:
+ if (diagnostics.get('source_unanswered') or diagnostics.get('unanswered')
+ or diagnostics.get('paused')):
+ raise _unanswered_error(diagnostics, str(error)) from error
raise
@@ -884,6 +912,13 @@ def _measure(transport: HttpTransport, candidates, record, *, minimum_width: int
for candidate in candidates:
try:
width, height = probe_size(transport, candidate, deadline=deadline)
+ except (SourceBudgetExhausted, InterruptedError):
+ raise
+ except SourcePaused:
+ record('paused')
+ record('unanswered')
+ answered += 1
+ continue
except httpx.TransportError as error:
record(_probe_failure(error))
record("unanswered")
@@ -930,6 +965,12 @@ def _download_best(transport: HttpTransport, measured, record, *, minimum_width:
try:
data = _fetch(transport, winner.url, referer=winner.referer,
limit=16 * 1024 * 1024, deadline=deadline)
+ except SourceBudgetExhausted:
+ raise
+ except SourcePaused:
+ record('paused')
+ record('download_failed')
+ continue
except (Unavailable, httpx.TransportError):
record("download_failed")
continue
diff --git a/src/peach/scraping_access.py b/src/peach/scraping_access.py
index 1ecd673ba..d5ef465f1 100644
--- a/src/peach/scraping_access.py
+++ b/src/peach/scraping_access.py
@@ -107,6 +107,10 @@ class SourcePaused(RuntimeError):
"""来源冷却期内停止请求,保留已有图像。"""
+class SourceBudgetExhausted(SourcePaused):
+ """本趟采集预算耗尽,不能作为单个来源的冷却跳过。"""
+
+
def cooldown_path(root: Path, source: str) -> Path:
"""这个来源的冷却记录。键是来源名;没有来源名的请求按主机名散列,见 `SourceTransport`。"""
return Path(root) / ("scraping-" + source + ".cooldown.json")
@@ -443,15 +447,15 @@ class SourceTransport:
request = HttpRequest(request.method, request.url,
{**headers, "Accept-Language": "zh-CN,zh;q=0.9"}, request.body)
if self.max_requests and self.requests >= self.max_requests:
- raise SourcePaused("本趟采集次数已用完,再跑一次接着采;已有图片保留")
+ raise SourceBudgetExhausted("本趟采集次数已用完,再跑一次接着采;已有图片保留")
if self.deadline:
timeout = min(timeout, self.deadline - time.monotonic())
if timeout <= 0:
- raise SourcePaused("本趟采集时间已用完,再跑一次接着采;已有图片保留")
+ raise SourceBudgetExhausted("本趟采集时间已用完,再跑一次接着采;已有图片保留")
if self.max_bytes:
remaining = self.max_bytes - self.bytes
if remaining <= 0:
- raise SourcePaused("本趟下载量已用完,再跑一次接着采;已有图片保留")
+ raise SourceBudgetExhausted("本趟下载量已用完,再跑一次接着采;已有图片保留")
max_bytes = min(max_bytes, remaining - 1)
key = source or hashlib.sha256(hostname_of(request.url).encode()).hexdigest()
cooldown = cooldown_path(self.root, key)
diff --git a/tests/test_jav_covers.py b/tests/test_jav_covers.py
index 07eb7a5da..745ed0363 100644
--- a/tests/test_jav_covers.py
+++ b/tests/test_jav_covers.py
@@ -5,6 +5,7 @@ import json
import sqlite3
import sys
import tempfile
+import time
import unittest
from pathlib import Path
from unittest.mock import call, patch
@@ -115,6 +116,122 @@ class FetchRetryTests(unittest.TestCase):
'SSIS-057', 0, prior_candidates=(cached,))
self.assertEqual((winner, size), (cached, (800, 540)))
+ def test_paused_catalogs_keep_an_already_available_candidate(self):
+ candidate = covers.candidate_for('https://official.example/cached.jpg')
+ for site, code in (('r18_evidence', 'SSIS-057'), ('mgstage_images', '200GANA-1995'),
+ ('prestige_images', 'ABW-192')):
+ with self.subTest(site=site), \
+ patch.object(covers, 'dmm_evidence', return_value=covers.MetadataEvidence()), \
+ patch.object(covers, 'r18_evidence', return_value=covers.MetadataEvidence()), \
+ patch.object(covers, 'mgstage_images', return_value=[]), \
+ patch.object(covers, 'prestige_images', return_value=[]), \
+ patch.object(covers, site, side_effect=covers.SourcePaused('来源正在冷却')):
+ winner, size, _ = covers.best_cover(
+ transport_for({candidate.url: (200, jpeg(800, 540))}), code, 0,
+ prior_candidates=(candidate,))
+ self.assertEqual((winner, size), (candidate, (800, 540)))
+
+ def test_a_paused_group_site_does_not_hide_the_other_sites_candidate(self):
+ candidate = covers.candidate_for('https://official.example/live.jpg')
+ for paused, available in (('prestige_images', 'mgstage_images'),
+ ('mgstage_images', 'prestige_images')):
+ with self.subTest(paused=paused), \
+ patch.object(covers, paused, side_effect=covers.SourcePaused('来源正在冷却')), \
+ patch.object(covers, available, return_value=[candidate]):
+ winner, _, _ = covers.best_cover(
+ transport_for({candidate.url: (200, jpeg(1600, 1080))}), 'ABW-192', 0)
+ self.assertEqual(winner, candidate)
+
+ def test_a_persisted_cooldown_keeps_the_cached_candidate_and_cooldown_record(self):
+ from peach.http import HttpResponse
+ from peach.scraping_access import SourceTransport, cooldown_path, pause_source
+ candidate = covers.candidate_for('https://available.example/cover.jpg')
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ pause_source(root, 'prestige', retry_after=60)
+ cooldown = cooldown_path(root, 'prestige')
+ before = cooldown.read_bytes()
+ transport = SourceTransport(root)
+ for site in ('mgstage', 'r18dev'):
+ transport.transports[site] = lambda *_args: HttpResponse(404, {}, b'')
+ transport.transports[None] = lambda *_args: HttpResponse(200, {}, jpeg(800, 540))
+ with patch('peach.scraping_access.client_for') as client:
+ winner, _, _ = covers.best_cover(transport, 'ABW-192', 0, prior_candidates=(candidate,))
+ self.assertEqual(winner, candidate)
+ self.assertEqual(cooldown.read_bytes(), before)
+ client.assert_not_called()
+
+ def test_a_paused_image_probe_or_download_keeps_other_candidates(self):
+ paused = covers.candidate_for('https://paused.example/cover.jpg')
+ available = covers.candidate_for('https://available.example/cover.jpg')
+ for phase in ('probe', 'download'):
+ def transport(request, _timeout, _limit, phase=phase):
+ if request.url == paused.url:
+ if phase == 'probe' or 'Range' not in request.headers:
+ raise covers.SourcePaused('来源正在冷却')
+ return _Response(200, jpeg(1600, 1080))
+ return _Response(200, jpeg(800, 540))
+ with self.subTest(phase=phase):
+ winner, _, _ = covers.best_cover(transport, 'FC2-PPV-123456', 0,
+ prior_candidates=(paused, available))
+ self.assertEqual(winner, available)
+
+ def test_unanswered_images_preserve_paused_and_other_failure_results(self):
+ first = covers.candidate_for('https://paused.example/cover.jpg')
+ second = covers.candidate_for('https://offline.example/cover.jpg')
+ for all_paused in (False, True):
+ def transport(request, _timeout, _limit, all_paused=all_paused):
+ if request.url == first.url or all_paused:
+ raise covers.SourcePaused('来源正在冷却')
+ return _Response(503, b'')
+ expected = covers.SourcePaused if all_paused else covers.Unavailable
+ with self.subTest(all_paused=all_paused):
+ with self.assertRaises(expected) as caught:
+ covers.best_cover(transport, 'FC2-PPV-123456', 0, prior_candidates=(first, second))
+ self.assertNotIsInstance(caught.exception, covers.NotFound)
+
+ def test_catalogs_that_are_all_paused_remain_paused_not_missing(self):
+ def transport(*_args):
+ raise covers.SourcePaused('来源正在冷却')
+ for code in ('SSIS-057', '200GANA-1995', 'ABW-192'):
+ with self.subTest(code=code), self.assertRaises(covers.SourcePaused):
+ covers.best_cover(transport, code, 0)
+
+ def test_a_spent_run_budget_stops_before_trying_another_candidate(self):
+ from peach.scraping_access import SourceTransport
+ candidates = tuple(covers.candidate_for(f'https://{name}.example/cover.jpg')
+ for name in ('first', 'second'))
+ with tempfile.TemporaryDirectory() as directory:
+ transports = [SourceTransport(Path(directory), max_requests=1),
+ SourceTransport(Path(directory), max_bytes=1),
+ SourceTransport(Path(directory), max_seconds=1)]
+ transports[0].requests = transports[1].bytes = 1
+ transports[2].deadline = time.monotonic() - 1
+ for transport in transports:
+ for code in ('FC2-PPV-123456', 'ABW-192', 'SSIS-057'):
+ with self.subTest(transport=transport, code=code), \
+ patch('peach.scraping_access.client_for') as client:
+ with self.assertRaises(covers.SourcePaused) as caught:
+ covers.best_cover(transport, code, 0, prior_candidates=candidates)
+ self.assertIn('本趟', str(caught.exception))
+ self.assertEqual(covers.failure_log_row(code, caught.exception)['outcome'], 'unavailable')
+ client.assert_not_called()
+
+ def test_image_checks_preserve_cancellation_and_deadline_exceptions(self):
+ from peach.processing_control import ItemSkipped
+ candidate = covers.candidate_for('https://official.example/full.jpg')
+ for error in (InterruptedError('处理任务已停止'), ItemSkipped('跳过当前项'),
+ covers.DeadlineExceeded('动作预算已用尽')):
+ for phase in ('probe', 'download'):
+ def transport(request, _timeout, _limit, phase=phase, error=error):
+ if phase == 'download' and 'Range' in request.headers:
+ return _Response(200, jpeg(800, 540))
+ raise error
+ with self.subTest(error=type(error).__name__, phase=phase):
+ with self.assertRaises(type(error)) as caught:
+ covers.best_cover(transport, 'FC2-PPV-123456', 0, prior_candidates=(candidate,))
+ self.assertIs(caught.exception, error)
+
def test_unanswered_catalogs_without_candidates_are_retryable(self):
diagnostics = {}
with patch.object(covers, 'dmm_evidence', side_effect=covers.httpx.ConnectError('TLS EOF')), \