Peach: Local-first video metadata scraper and media manager.
perf(web): 复核、口味与垃圾复核的聚合缓存改活 15 分钟
longmeidao5a333729ed38
diff --git a/src/peach/api.py b/src/peach/api.pyindex b399e444c..151015c6b 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -245,6 +245,7 @@ def create_app(mounts=location_mounts(),available=_writer(sync),ffprobe=resolver.ffprobe,+ after_ingest=contract.cache_bust,)contract.follow_scheduler = follow_scheduler# 订阅源拉取(ADR-0042)用同一个调度实现,只换 job id、状态文件与默认间隔。diff --git a/src/peach/push_discovery.py b/src/peach/push_discovery.pyindex 17ebc689c..13a48f723 100644--- a/src/peach/push_discovery.py+++ b/src/peach/push_discovery.py@@ -598,10 +598,14 @@ class PushDiscoveryService:declared_roots, mounts, available: bool = True,debounce: float = DEBOUNCE_SECONDS, settle: float = SETTLE_SECONDS,ffprobe: Callable[[], object] | None = None,+ after_ingest: Callable[[], None] | None = None,):self.settings = PushDiscoverySettings(state_root)#: 取 ffprobe 的回调,登记完视频当场探时长用;每次现取,装上 FFmpeg 不必重启。self.ffprobe = ffprobe+ #: 登记落库之后调一次。入库走 `scan` 自己的连接,不经过 `write_transaction`,+ #: 服务里的聚合缓存靠它作废,新文件才会立刻出现在统计与复核里。+ self.after_ingest = after_ingestself.secret = WebhookSecret(secrets_root)self.db_path = Path(db_path)self.declared_roots = {key: tuple(value) for key, value in declared_roots.items()}@@ -636,6 +640,8 @@ class PushDiscoveryService:# 附属文件按「处理完了」计:文件在,只是按规则不登记,不是「文件不在」。if result.found and not result.sidecar:self._measure(location, path)+ if result.found and self.after_ingest:+ self.after_ingest()return result.founddef _measure(self, location: str, path: str) -> None:diff --git a/src/peach/review_csv.py b/src/peach/review_csv.pyindex ca7e761f8..9b3c51e20 100644--- a/src/peach/review_csv.py+++ b/src/peach/review_csv.py@@ -154,6 +154,18 @@ def latest_candidate_file(category: str, root: Path | None = None) -> Path | NonMULTI_BATCH_CATEGORIES = frozenset({"metadata_fields"})+def candidate_root_version(root: Path | None = None) -> int | None:+ """候选目录的修改时间,读缓存拿它当键的一部分。++ 候选文件都直接放在这一层:新增批次、改名替换与删除都会改它,原地覆写不会,+ 那一种由缓存的时间上限兜底。+ """+ try:+ return (root or GENERATED_DIR).stat().st_mtime_ns+ except OSError:+ return None++def candidate_files(category: str, root: Path | None = None) -> list[Path]:"""这一类的候选文件,按证据优先级排列:先读的那份说了算。diff --git a/src/peach/web_batch.py b/src/peach/web_batch.pyindex 179f2ff9c..5810c04bf 100644--- a/src/peach/web_batch.py+++ b/src/peach/web_batch.py@@ -28,7 +28,7 @@ from .task_runs import TaskRunHandlefrom .web_activity import DEFAULT_PROFILE_IDfrom .web_catalog import COST, attach_card_performersfrom .web_resource_sync import clean_resource_orphans, vanished_asset_rows-from .web_state import WebContract+from .web_state import LEDGER_AGGREGATE_TTL, WebContract#: 批量操作在活动页上的名字。表里存 `operation`,人看的是这一列。BATCH_LABELS = {@@ -273,6 +273,36 @@ def q_ads(contract: WebContract, limit=200, offset=0, kind="", status="pending")raise ValueError("invalid junk kind")if status not in {"pending", "dismissed"}:raise ValueError("invalid junk status")+ out, dismissed_ids = contract.cached(+ "junk-scored", lambda: _scored_junk(contract), ttl=LEDGER_AGGREGATE_TTL)+ pending = [item for item in out if item["id"] not in dismissed_ids]+ dismissed = [item for item in out if item["id"] in dismissed_ids]+ pool = dismissed if status == "dismissed" else pending+ counts = {junk_kind: 0 for junk_kind in JUNK_KINDS}+ for item in pool:+ counts[item["junk_kind"]] += 1+ filtered = [item for item in pool if not kind or item["junk_kind"] == kind]+ # 缓存里那份是共享的,这一页的条目复制出来再挂演员,不改到下一次请求。+ items = [dict(item) for item in filtered[offset:offset + limit]]+ attach_card_performers(+ contract, [item for item in items if item.get("medium") == "video"])+ return {+ "total": len(filtered),+ "all_total": len(pool),+ "pending_total": len(pending),+ "dismissed_total": len(dismissed),+ "counts": counts,+ "kind": kind,+ "status": status,+ "items": items,+ }+++def _scored_junk(contract: WebContract) -> tuple[list[dict], frozenset[int]]:+ """全部候选按嫌疑分从高到低,连同用户已确认不是垃圾的 id。++ 与请求的类型、状态和分页无关:整份算一次(真实账本上两三秒),`q_ads` 按参数切。+ """with contract.read_connection() as c:rows = _junk_rows(c)# 同番号是否存在明显更长的版本;只在 code 是真番号时才有意义。@@ -397,26 +427,7 @@ def q_ads(contract: WebContract, limit=200, offset=0, kind="", status="pending")d.pop("path", None)out.append(d)out.sort(key=lambda x: (-x["score"], -(x["size"] or 0)))- pending = [item for item in out if item["id"] not in dismissed_ids]- dismissed = [item for item in out if item["id"] in dismissed_ids]- pool = dismissed if status == "dismissed" else pending- counts = {junk_kind: 0 for junk_kind in JUNK_KINDS}- for item in pool:- counts[item["junk_kind"]] += 1- filtered = [item for item in pool if not kind or item["junk_kind"] == kind]- items = filtered[offset:offset + limit]- attach_card_performers(- contract, [item for item in items if item.get("medium") == "video"])- return {- "total": len(filtered),- "all_total": len(pool),- "pending_total": len(pending),- "dismissed_total": len(dismissed),- "counts": counts,- "kind": kind,- "status": status,- "items": items,- }+ return out, frozenset(dismissed_ids)def _restore_staged_media(staged):diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 2e6cd08f3..33bc3fc92 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -11,6 +11,7 @@from __future__ import annotationsfrom .follow_discovery import MAX_SUGGESTIONS, MAX_TERM_LENGTH+from .review_csv import candidate_root_versionfrom .web_activity import (w_activity,w_feedback,@@ -88,7 +89,7 @@ from .web_scraping import (q_scraping, q_scraping_amane_bridge, w_scraping_amane_check, w_scraping_amane_rebuild,w_scraping_check, w_scraping_cover, w_scraping_settings,)-from .web_state import WebContract+from .web_state import LEDGER_AGGREGATE_TTL, WebContractfrom .web_tasks import q_tasksfrom .web_timeline_thumbnails import q_thumbnail_jobs, q_timeline, w_thumbnail_jobsfrom .web_stats import (@@ -229,11 +230,15 @@ def _get_taste(contract, args):return contract.cached(f"taste:{window}",lambda: q_taste(contract, {"window": window}),+ ttl=LEDGER_AGGREGATE_TTL,)def _get_review(contract, args):- payload = contract.cached("review", lambda: q_review(contract))+ # 候选文件由进程外的抓取脚本写,目录一变键就变;账本写入照常经 `cache_bust` 作废。+ version = candidate_root_version(getattr(contract, "candidate_root", None))+ payload = contract.cached(f"review:{version}", lambda: q_review(contract),+ ttl=LEDGER_AGGREGATE_TTL)# 数据管理页只要一个待复核条数。完整 payload 带着每条候选的全文,实测是# 兆级;卡片上的一个数字不值这趟传输,但计数本身仍来自同一份缓存快照,# 不另立一套口径。diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 763700454..ee517fb5b 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -7,7 +7,7 @@`web_catalog`、`web_entity`、`web_stats`、`web_batch` 全都 import 它,所以它一旦反过来 import 其中任何一个,整层立刻循环。判据就是这个文件里不许出现 `from .web_`。-`CACHE_TTL` 归这里是因为使用者只有本文件的 `cached()`/`cached_lru()`。内联 favicon 也放这里:它是+`CACHE_TTL` 与 `LEDGER_AGGREGATE_TTL` 归这里,因为它们量的是本文件 `cached()`/`cached_lru()` 的寿命。内联 favicon 也放这里:它是唯一一个没有磁盘文件的静态资源,而 `api` 一直从契约模块取它,这次只搬位置。"""from __future__ import annotations@@ -62,6 +62,11 @@ class AvatarRootIndex(NamedTuple):FAVICON = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0B0B0D"/><defs><linearGradient id="pg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#FF9A76"/><stop offset="1" stop-color="#F2557B"/></linearGradient></defs><path d="M16 28c-5.7 0-9.7-3.6-9.7-8.6 0-4.3 2.8-7.6 6.5-7.6 1.4 0 2.4.5 3.2 1.1.8-.6 1.8-1.1 3.2-1.1 3.7 0 6.5 3.3 6.5 7.6C25.7 24.4 21.7 28 16 28z" fill="url(#pg)"/><path d="M16 13.4V27" stroke="#0B0B0D" stroke-width="1.1" opacity=".3" stroke-linecap="round"/><path d="M17.1 11.7c.6-2.8 2.8-4.6 5.6-4.8-.2 2.8-2.2 4.7-5.6 4.8z" fill="#5FB95F"/><path d="M16 11.9c0-1.9.5-3.4 1.5-4.5" stroke="#8A5A3B" stroke-width="1.5" stroke-linecap="round" fill="none"/></svg>')CACHE_TTL = 90+#: 只读账本的重聚合(复核、口味、垃圾复核)的寿命。服务进程内的写入一律经+#: `after_commit` 或显式 `cache_bust()` 作废缓存,这个上限兜的只是进程外的写:+#: CLI 的 `--apply` 脚本与账本同步拉库落库后,这几页最多滞后这么久。+#: 磁盘扫描类索引(封面、厂牌 Logo、头像目录)外部脚本随时往里放文件,仍用 `CACHE_TTL`。+LEDGER_AGGREGATE_TTL = 15 * 60class WebContract:@@ -206,7 +211,7 @@ class WebContract:return BackgroundJob(name, id_key=id_key, task_key=task_key,runs=self.task_runs, followup_runner=self.followups)- def cached(self, key, fn):+ def cached(self, key, fn, *, ttl: float = CACHE_TTL):"""带 TTL 的读缓存。`fn` 刻意在锁外算——它会读 CSV、查库,拿着锁算会把并发请求全串起来。@@ -220,7 +225,7 @@ class WebContract:now = time.monotonic()with self.cache_lock:hit = self.cache.get(key)- if hit and now - hit[0] < CACHE_TTL:+ if hit and now - hit[0] < ttl:self.cache.move_to_end(key)return hit[1]generation = self.cache_generationdiff --git a/tests/test_ad_judgement.py b/tests/test_ad_judgement.pyindex e776dbb49..16abc3a97 100644--- a/tests/test_ad_judgement.py+++ b/tests/test_ad_judgement.py@@ -7,7 +7,9 @@ import sqlite3import tempfileimport unittestfrom pathlib import Path+from unittest import mock+from peach import web_batchfrom peach.web_contract import (BUNDLE_DIR_ASSETS,CONTENT_BYTES,@@ -248,6 +250,21 @@ class ResourceJunkQueueTests(unittest.TestCase):w_batch(self.contract, {"ids": [20], "operation": "reconsider-junk"})self.assertEqual(q_ads(self.contract, limit=200)["pending_total"], 3)++ def test_one_scoring_serves_every_kind_status_and_page(self):+ """打分与类型、状态、分页无关:算一次,各种切法共用;一页里的条目改不到下一页。"""+ self.add(30, "115", r"B:\\广告\\hayob9.com.jpg", "image", 28000)+ self.add(31, "115", r"B:\\MIB\\Mib19.com.zip", "archive", 14 * 1024**3)+ with mock.patch.object(web_batch, "_scored_junk", wraps=web_batch._scored_junk) as scored:+ first = q_ads(self.contract, limit=1)+ archives = q_ads(self.contract, limit=200, kind="archive")+ dismissed = q_ads(self.contract, limit=200, status="dismissed")+ self.assertEqual(scored.call_count, 1)+ self.assertEqual(first["total"], 2)+ self.assertEqual([item["id"] for item in archives["items"]], [31])+ self.assertEqual(dismissed["items"], [])+ first["items"][0]["why"] = ["被改过"]+ self.assertNotEqual(q_ads(self.contract, limit=1)["items"][0]["why"], ["被改过"])self.assertEqual(q_ads(self.contract, limit=200, status="dismissed")["items"], [])diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.pyindex 3e1486e27..632a04c7a 100644--- a/tests/test_complexity_ratchet.py+++ b/tests/test_complexity_ratchet.py@@ -35,7 +35,7 @@ LIMIT = 30#: 键是 `<仓库相对路径>:<限定名>`,值是当前的分支数,只能往下改。BASELINE: dict[str, int] = {- "src/peach/web_batch.py:q_ads": 85,+ "src/peach/web_batch.py:_scored_junk": 68,"scripts/scrape_codes.py:_scrape": 35,"scripts/localize_performer_names.py:collect": 64,"src/peach/web_resource_sync.py:_resource_orphan_plan": 60,diff --git a/tests/test_push_discovery.py b/tests/test_push_discovery.pyindex 83533e09c..184a0a550 100644--- a/tests/test_push_discovery.py+++ b/tests/test_push_discovery.py@@ -395,6 +395,17 @@ class IngestPathTests(_ServiceCase):self.assertEqual(self.rows(), {})+class IngestNotifiesTests(_ServiceCase):+ def test_a_registered_file_tells_the_service_its_caches_are_stale(self):+ """入库走扫描自己的连接;不通知的话,统计与复核要等缓存过期才看见新文件。"""+ (self.media / "a.mp4").write_bytes(b"0" * 4)+ notified = []+ service = self.service(after_ingest=lambda: notified.append(True))+ self.assertTrue(service._ingest("local", self.ledger("local", "a.mp4")))+ self.assertFalse(service._ingest("local", self.ledger("local", "gone.mp4")))+ self.assertEqual(notified, [True])++class SettingsTests(_ServiceCase):def test_a_prefix_pointing_at_an_unknown_root_is_refused_on_save(self):service = self.service()diff --git a/tests/test_web_review.py b/tests/test_web_review.pyindex 77d5db2db..a5ba999fb 100644--- a/tests/test_web_review.py+++ b/tests/test_web_review.py@@ -148,6 +148,17 @@ class ReviewQueueTests(unittest.TestCase):def _auto(self):return auto_apply_metadata(self.contract.database, self.candidates)+ def test_a_new_candidate_file_shows_up_without_waiting_for_the_cache(self):+ """候选文件由进程外的脚本写,没有 `cache_bust`;目录一变,复核页就要重算。"""+ before = rm_web.dispatch_api_get(self.contract, "/api/review", {})+ self.write_logo_candidates([{+ "studio": "Moodyz", "handle": "moodyz", "platform": "x",+ "resolved_url": "https://example.test/moodyz.png", "saved": "", "accepted": "",+ }])+ after = rm_web.dispatch_api_get(self.contract, "/api/review", {})+ self.assertIsNone(before["sources"]["studio_logos"])+ self.assertEqual(after["sources"]["studio_logos"], "studio-logo-candidate-20260818.csv")+def test_auto_apply_commits_in_batches_and_keeps_what_landed_before_a_stop(self):"""整库一趟能有上万条。一个事务包到底的话,写锁全程被占着,界面上的复核与编辑都得排队;任务中途停下来,已经判完的也跟着回滚。分批提交两头都解决。