Peach: Local-first video metadata scraper and media manager.
fix(transcodes): per-asset 锁加引用计数清理,长跑不再只增不减
longmeidao1a568ec05506
diff --git a/src/peach/transcodes.py b/src/peach/transcodes.pyindex 3e2d36885..da6d817df 100644--- a/src/peach/transcodes.py+++ b/src/peach/transcodes.py@@ -5,6 +5,7 @@ import subprocessimport threadingimport timeimport uuid+from contextlib import contextmanagerfrom pathlib import Pathfrom .ffmpeg import FFmpegResolver@@ -29,7 +30,7 @@ class TranscodeService:):self.resolver = resolverself.cache_root = cache_root- self._locks: dict[int, threading.Lock] = {}+ self._locks: dict[int, list] = {}self._locks_guard = threading.Lock()self._slots = threading.Semaphore(max(1, max_concurrent))@@ -114,6 +115,25 @@ class TranscodeService:stale.unlink(missing_ok=True)return target, True- def _lock_for(self, asset_id: int) -> threading.Lock:+ @contextmanager+ def _lock_for(self, asset_id: int):+ """同一 asset 的转码互斥;引用归零的条目随手清掉,长跑不再只增不减。++ 清理之所以安全:任何等锁线程都先在 guard 里加过引用,持有者退出临界区、+ 释放锁之后再减引用。减到零的那一刻不可能还有持有者或等待者,此时删除+ 才不会让后来的线程拿到第二把锁绕过互斥。+ """with self._locks_guard:- return self._locks.setdefault(asset_id, threading.Lock())+ entry = self._locks.get(asset_id)+ if entry is None:+ entry = [threading.Lock(), 0]+ self._locks[asset_id] = entry+ entry[1] += 1+ try:+ with entry[0]:+ yield+ finally:+ with self._locks_guard:+ entry[1] -= 1+ if entry[1] <= 0:+ self._locks.pop(asset_id, None)diff --git a/tests/test_transcodes.py b/tests/test_transcodes.pyindex d8efa0909..1549418d9 100644--- a/tests/test_transcodes.py+++ b/tests/test_transcodes.py@@ -1,5 +1,6 @@import subprocessimport tempfile+import threadingimport unittestfrom pathlib import Pathfrom unittest.mock import patch@@ -16,6 +17,19 @@ class _Resolver:return BinaryChoice(self.binary, "test") if self.binary else None+class _FakeTranscode:+ """让 Popen 立即产出缓存文件的最小替身。"""++ returncode = 0++ def __init__(self, command, **_kwargs):+ self.command = command++ def communicate(self, timeout=None):+ Path(self.command[-1]).write_bytes(b"mp4")+ return b"", b""++class TranscodeServiceTests(unittest.TestCase):def test_native_mp4_is_returned_without_ffmpeg(self):source = Path("movie.mp4")@@ -54,6 +68,45 @@ class TranscodeServiceTests(unittest.TestCase):self.assertEqual(execute.call_count, 1)self.assertIn("libx264", execute.call_args.args[0])+ def test_lock_entries_do_not_accumulate_after_transcodes(self):+ """每把 per-asset 锁在没人持有、没人等待时必须从字典里消失。"""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.avi"+ source.write_bytes(b"avi")+ service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")++ with patch("peach.transcodes.subprocess.Popen", side_effect=_FakeTranscode):+ service.browser_path(9, source)+ self.assertEqual(service._locks, {})++ def test_concurrent_transcodes_of_one_asset_stay_serialised(self):+ """清理之后同 asset 并发仍互斥:两个线程同时转码,FFmpeg 只真跑一次。"""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "movie.avi"+ source.write_bytes(b"avi")+ service = TranscodeService(_Resolver(root / "ffmpeg.exe"), root / "cache")+ start = threading.Barrier(2)+ outcomes: list[bool] = []++ def worker():+ start.wait()+ _, transcoded = service.browser_path(9, source)+ outcomes.append(transcoded)++ with patch("peach.transcodes.subprocess.Popen",+ side_effect=_FakeTranscode) as execute:+ threads = [threading.Thread(target=worker) for _ in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ self.assertEqual(sorted(outcomes), [True, True])+ self.assertEqual(execute.call_count, 1,+ "第二个线程应命中缓存或等锁,不得重复转码")+ self.assertEqual(service._locks, {})+def test_session_cancellation_kills_an_active_transcode(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)