Skip to content

armgit / peach

Public Imported from GitHub
0

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

perf(api): 封面索引只认封面目录的修改时间

longmeidao15dce939074c
diff --git a/scripts/detect_cover_faces.py b/scripts/detect_cover_faces.py
index d4dc8dc1c..e9be6d0f8 100644
--- a/scripts/detect_cover_faces.py
+++ b/scripts/detect_cover_faces.py
@@ -31,6 +31,7 @@ if str(SRC_DIR) not in sys.path:
from peach.config import COVER_DIR
from peach.cover_artwork import FACE_ALGORITHM_VERSION, face_record
from peach.face_detect import FaceDetector, FaceModelUnavailable
+from peach.fsutil import atomic_write_text
from peach.jav_poster_crop import read_sidecar
@@ -79,8 +80,8 @@ def run(args: argparse.Namespace) -> int:
print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)
continue
stats["face" if result["face"] else "none"] += 1
- path.with_suffix(".face.json").write_text(
- json.dumps(result, ensure_ascii=False), encoding="utf-8")
+ # 换名写入:服务的封面索引只认目录修改时间,原地覆写不会让它重读。
+ atomic_write_text(path.with_suffix(".face.json"), json.dumps(result, ensure_ascii=False))
print(f"\n检出 {stats['face']},未检出 {stats['none']},读图失败 {stats['unreadable']}")
print("未检出的会退回固定取景,不影响显示。")
return 0
diff --git a/src/peach/jav_poster_crop.py b/src/peach/jav_poster_crop.py
index 1a4ee3c77..760bb6d32 100644
--- a/src/peach/jav_poster_crop.py
+++ b/src/peach/jav_poster_crop.py
@@ -49,6 +49,7 @@ from pathlib import Path
from typing import NamedTuple
from . import images
+from .fsutil import atomic_write_text
from .catalog_rules import (
is_jav_code,
is_korean_mib_code,
@@ -613,9 +614,8 @@ def read_sidecar(image_path: Path | str) -> dict | None:
def write_sidecar(image_path: Path | str, record: dict) -> Path:
- path = sidecar_path(image_path)
- path.write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8")
- return path
+ """先写临时文件再换名:服务的封面索引只认目录修改时间,原地覆写不会让它重读。"""
+ return atomic_write_text(sidecar_path(image_path), json.dumps(record, ensure_ascii=False))
def is_current(record: dict | None, width: int, height: int) -> bool:
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index 9ca631ee1..98ae21a4d 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -247,7 +247,9 @@ class WebContract:
`w_review_decision` 调 `cache_bust`;旧实现照样把批准前的快照写回去,
于是用户批准完刷新,看到的还是批准前的列表,而且持续整整一个 TTL。
- 用代次挡住:写回前确认这期间没有失效过,否则丢弃这次结果。
+ 用代次挡住:写回前确认这期间没有失效过,否则丢弃这次结果。按版本核验的键
+ (`revision_cache_keys`)不挡:版本在计算前读好,期间有写入,下一次读到新版本
+ 照样重算;挡掉它们只会让长任务频繁提交时上秒的计算永远存不进去,每个读者各算一遍。
"""
now = time.monotonic()
with self.cache_lock:
@@ -258,7 +260,7 @@ class WebContract:
generation = self.cache_generation
value = fn()
with self.cache_lock:
- if generation == self.cache_generation:
+ if generation == self.cache_generation or key in self.revision_cache_keys:
# 时间戳沿用进入时的 now:算得比 TTL 还久的结果直接算过期,
# 宁可下次重算,也不要把一份已经旧了的数据当新的用。
self.cache[key] = (now, version, value)
@@ -393,14 +395,20 @@ class WebContract:
`.poster.json` 说正封那一块在哪。版本见 `cover_version`。
卡片列表逐行问「有封面吗」「取景是多少」,一页 60 行就是 120+ 次 stat 加
- 读文件;封面目录一次 scandir 就覆盖全部番号,结果走 `cached()` 的 TTL。
- `/cover` 端点仍走 `cover_path()` 直读,取图不受索引影响。
+ 读文件;封面目录一次 scandir 就覆盖全部番号。`/cover` 端点仍走 `cover_path()`
+ 直读,取图不受索引影响。
- 键里带目录的修改时间:新落盘或换名替换的封面立刻进索引,按版本缓存的聚合
- (复核)重算时拿到的也是这一份。原地覆写的边车最多一个 TTL 后生效。
+ 索引只认封面目录的修改时间,不随账本提交失效,也不按时间过期:重建要读两千多份
+ 边车,约一秒。封面与边车的写入方(`cover_artwork.install_cover`、
+ `jav_poster_crop.write_sidecar`)都先写临时文件再换名,新增、替换、删除都会改
+ 目录时间。目录不存在时退回 `CACHE_TTL`。
"""
- return self.cached("cover-index", self._scan_cover_root,
- version=path_version(self.cover_root))
+ version = path_version(self.cover_root)
+ if version is None:
+ return self.cached("cover-index", self._scan_cover_root, version=None)
+ with self.cache_lock:
+ self.revision_cache_keys.add("cover-index")
+ return self.cached("cover-index", self._scan_cover_root, ttl=math.inf, version=version)
def _scan_cover_root(self) -> dict[str, dict]:
"""一次目录扫描同时收集封面存在性和两份 sidecar。目录不存在就是空索引。"""
diff --git a/tests/test_feeds_web.py b/tests/test_feeds_web.py
index 93c75366f..5fd63dab6 100644
--- a/tests/test_feeds_web.py
+++ b/tests/test_feeds_web.py
@@ -178,13 +178,13 @@ class FeedWebTest(FeedWebFixture):
target = self.contract.cover_root / 'SSIS-950.jpg'
target.parent.mkdir(parents=True, exist_ok=True)
Image.new('RGB', (800, 538)).save(target)
+ from peach.fsutil import atomic_write_text
+ # 来源边车与 `install_cover` 一样换名写入:封面索引只认封面目录的修改时间。
evidence = target.with_suffix('.scraping.json')
- evidence.write_text(json.dumps({'source_url': 'https://c0.jdbstatic.com/covers/a.jpg'}), encoding='utf-8')
- self.contract.cache_bust()
+ atomic_write_text(evidence, json.dumps({'source_url': 'https://c0.jdbstatic.com/covers/a.jpg'}))
self.assertFalse(self.contract.has_cover('SSIS-950'))
self.assertIsNone(self.contract.cover_path('SSIS-950'))
- evidence.write_text(json.dumps({'source_url': 'https://pics.dmm.co.jp/a.jpg'}), encoding='utf-8')
- self.contract.cache_bust()
+ atomic_write_text(evidence, json.dumps({'source_url': 'https://pics.dmm.co.jp/a.jpg'}))
self.assertTrue(self.contract.has_cover('SSIS-950'))
self.assertEqual(self.contract.cover_path('SSIS-950'), target)
diff --git a/tests/test_ledger_revision.py b/tests/test_ledger_revision.py
index cf035ef21..987426086 100644
--- a/tests/test_ledger_revision.py
+++ b/tests/test_ledger_revision.py
@@ -118,6 +118,54 @@ class LedgerRevisionTests(unittest.TestCase):
return_value=1000.0 + web_state.CACHE_TTL):
self.assertEqual(self.contract.cached_until_changed("ads", self.compute), 2)
+ def test_a_commit_during_a_versioned_computation_keeps_the_result(self):
+ def derive():
+ self.calls += 1
+ self.contract.cache_bust()
+ return self.calls
+ self.assertEqual(self.contract.cached_until_changed("catalog", derive, tables=("asset",)), 1)
+ self.assertEqual(self.contract.cached_until_changed("catalog", derive, tables=("asset",)), 1)
+
+
+class CoverIndexTests(unittest.TestCase):
+ """封面索引只认封面目录:账本提交与时间都不让它重扫,换名写入的封面与边车立刻生效。"""
+
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.db_path = fresh_ledger(self.directory.name)
+ self.covers = Path(self.directory.name) / "covers"
+ self.covers.mkdir()
+ (self.covers / "ABC-001.jpg").write_bytes(b"jpg")
+ self.contract = WebContract(self.db_path, cover_root=self.covers)
+ self.scans = mock.patch.object(
+ self.contract, "_scan_cover_root", wraps=self.contract._scan_cover_root).start()
+ self.addCleanup(mock.patch.stopall)
+
+ def test_commits_and_elapsed_time_keep_the_index(self):
+ self.assertTrue(self.contract.has_cover("ABC-001"))
+ self.contract.cache_bust()
+ insert_asset(self.db_path, 1)
+ with mock.patch.object(web_state.time, "monotonic",
+ return_value=web_state.time.monotonic() + 10 * web_state.CACHE_TTL):
+ self.assertTrue(self.contract.has_cover("ABC-001"))
+ self.assertEqual(self.scans.call_count, 1)
+
+ def test_rewritten_sidecars_and_added_or_removed_covers_show_up_at_once(self):
+ from peach import jav_poster_crop
+ self.assertIsNone(self.contract.poster_box("ABC-001"))
+ jav_poster_crop.write_sidecar(self.covers / "ABC-001.jpg", jav_poster_crop.manual_record(
+ 800, 538, {"x0": 420, "y0": 0, "x1": 800, "y1": 538}))
+ self.assertEqual(self.contract.poster_box("ABC-001")["x0"], 420)
+ jav_poster_crop.write_sidecar(self.covers / "ABC-001.jpg", jav_poster_crop.manual_record(
+ 800, 538, {"x0": 400, "y0": 0, "x1": 800, "y1": 538}))
+ self.assertEqual(self.contract.poster_box("ABC-001")["x0"], 400)
+ self.assertFalse(self.contract.has_cover("XYZ-002"))
+ (self.covers / "XYZ-002.jpg").write_bytes(b"jpg")
+ self.assertTrue(self.contract.has_cover("XYZ-002"))
+ (self.covers / "XYZ-002.jpg").unlink()
+ self.assertFalse(self.contract.has_cover("XYZ-002"))
+
if __name__ == "__main__":
unittest.main()