Peach: Local-first video metadata scraper and media manager.
fix(metadata): 复用发现快照并分离缓存读取生命周期
longmeidaob8b8552d71b1
diff --git a/src/peach/javdb_public.py b/src/peach/javdb_public.pyindex 3b1886e2c..461c714e3 100644--- a/src/peach/javdb_public.py+++ b/src/peach/javdb_public.py@@ -234,24 +234,34 @@ class PublicAPI:root = self._store().rootreturn f'{root.resolve()}\0{key}' if root is not None else key+ def _memory(self, cache_key, *, image, refresh):+ """持有缓存锁时读取内存命中或失败冷却,返回内容及实际来源状态。"""+ hit = self.cache.get(cache_key)+ snapshot = self.snapshots.get(cache_key)+ failed = self.failures.get(cache_key)+ cooling = failed is not None and failed[0] > self.clock()+ error = str(failed[1]) if cooling else ''+ if (not refresh and hit and hit[0] > self.clock()+ and (image or (snapshot is not None and snapshot.fresh(self.wallclock())))):+ self.cache.move_to_end(cache_key)+ return hit[1], snapshot, error+ if cooling:+ if snapshot is not None:+ return snapshot.value, snapshot, error+ raise failed[1]+ return None+def _cached(self, key, fetch, *, released=None, refresh=False):cache_key = self._cache_key(key)image = key.startswith('image:')store = self._store()with self.lock:- hit = self.cache.get(cache_key)+ memory = self._memory(cache_key, image=image, refresh=refresh)+ if memory is not None:+ result, snapshot, error = memory+ _record_read(key, snapshot, error)+ return resultsnapshot = self.snapshots.get(cache_key)- failed = self.failures.get(cache_key)- if (not refresh and hit and hit[0] > self.clock()- and (image or (snapshot is not None and snapshot.fresh(self.wallclock())))):- self.cache.move_to_end(cache_key)- _record_read(key, snapshot, str(failed[1]) if failed and failed[0] > self.clock() else '')- return hit[1]- if failed and failed[0] > self.clock():- if snapshot is not None:- _record_read(key, snapshot, str(failed[1]))- return snapshot.value- raise failed[1]future = self.pending.get(cache_key)owner = future is Noneif owner:@@ -369,6 +379,7 @@ class PublicAPI:hit = self.cache.get(cache_key)snapshot = self.snapshots.get(cache_key) or self._store().load(key)if snapshot and snapshot.fresh(self.wallclock()):+ _record_read(key, snapshot)return dict(snapshot.value) if isinstance(snapshot.value, dict) else Nonereturn dict(hit[1]) if hit and hit[0] > self.clock() and snapshot is None else Nonediff --git a/src/peach/web_jav_discovery.py b/src/peach/web_jav_discovery.pyindex 94ffef60a..41e61c88d 100644--- a/src/peach/web_jav_discovery.py+++ b/src/peach/web_jav_discovery.py@@ -16,13 +16,16 @@ def _identity(connection, kind, name):def _cached_movie(code, contract):- from .javdb_public import PUBLIC_API+ from .javdb_public import PUBLIC_API, public_cache_scope, cache_checked_atmetadata = discovery_metadata(contract)stored, _ = metadata.peek(code)- memory = PUBLIC_API.peek_movie(code)- if memory and not stored:- metadata.remember(code, memory)- return stored or memory or {}+ if stored:+ return stored+ with public_cache_scope(contract.cover_root.parent / 'jav-public'):+ source = PUBLIC_API.peek_movie(code)+ if source:+ metadata.remember(code, source, checked_at=cache_checked_at('movie:' + code, exact=True))+ return source or {}def _external(connection, contract):diff --git a/tests/test_jav_cache.py b/tests/test_jav_cache.pyindex 7a4426c6e..ef7771edf 100644--- a/tests/test_jav_cache.py+++ b/tests/test_jav_cache.py@@ -5,7 +5,8 @@ from pathlib import Pathimport unittestfrom concurrent.futures import ThreadPoolExecutorfrom threading import Event-from unittest.mock import Mock+from unittest.mock import Mock, patch+from types import SimpleNamespacefrom peach.jav_cache import DAY, PublicSnapshots, cache_fresh, cache_lifetime, stable_afterfrom peach.javdb_public import PublicAPI, PublicSourceUnavailable, public_cache_scope, cache_checked_at@@ -101,6 +102,22 @@ class PublicationCacheTests(unittest.TestCase):self.assertEqual(api.media_movie('EXM-001')['cover_url'], 'https://tp.spfcas.com/current.jpg')self.assertEqual(api._json.call_count, 1)+ def test_discovery_rebuilds_a_missing_projection_from_the_fixed_source_timestamp(self):+ from peach.jav_discovery_metadata import DiscoveryMetadata+ from peach.web_jav_discovery import _cached_movie+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ now = [stamp('2026-10-13')]+ movie = {'number': 'EXM-001', 'release_date': '2020-01-01', 'tags': [], 'score': 4, 'duration': 120}+ self.api(root / 'jav-public', now)._cached('movie:EXM-001', lambda: movie)+ now[0] += 10 * DAY+ reader = self.api(root / 'jav-public', now)+ metadata = DiscoveryMetadata(root / 'metadata.json', api=reader, clock=lambda: now[0])+ contract = SimpleNamespace(cover_root=root / 'covers')+ with patch('peach.javdb_public.PUBLIC_API', reader), patch('peach.web_jav_discovery.discovery_metadata', return_value=metadata):+ self.assertEqual(_cached_movie('EXM-001', contract), movie)+ self.assertEqual(metadata.peek('EXM-001')[1]['metadata_checked_at'], stamp('2026-10-13'))+def test_month_end_and_leap_year_boundaries(self):self.assertEqual(stable_after('2024-01-31'), date(2024, 2, 29))self.assertEqual(stable_after('2026-01-31'), date(2026, 2, 28))@@ -140,3 +157,11 @@ class PublicationCacheTests(unittest.TestCase):future = PublicSnapshots(Path(directory).resolve(), clock=lambda: 200)future.save('movie:EXM-001', {'id': 'Exact'}, None)self.assertIsNone(store.load('movie:EXM-001'))++ def test_unavailable_source_with_empty_message_still_obeys_failure_cooldown(self):+ api = PublicAPI()+ fetch = Mock(side_effect=PublicSourceUnavailable())+ for _ in range(2):+ with self.assertRaises(PublicSourceUnavailable):+ api._cached('reviews:Exact:1', fetch)+ self.assertEqual(fetch.call_count, 1)