Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(segments): 计划缓存一满就 clear 改为 LRU 逐出,上限 256 不变

longmeidao5b94822f8ff1
diff --git a/src/peach/segments.py b/src/peach/segments.py
index 49cfae3a8..6c3332914 100644
--- a/src/peach/segments.py
+++ b/src/peach/segments.py
@@ -5,6 +5,7 @@ import asyncio
import os
import subprocess
import uuid
+from collections import OrderedDict
from pathlib import Path
from .ffmpeg import FFmpegResolver
@@ -14,6 +15,7 @@ from .streaming import StreamSessionRegistry
HLS_SEGMENT_SECONDS = 6
# 片段缓存上限。超了按最后访问时间淘汰;片段可再生,丢了只是重跑一次 FFmpeg。
DEFAULT_CACHE_BYTES = 2 << 30
+PLAN_CACHE_LIMIT = 256
class SegmentUnavailable(RuntimeError):
@@ -62,7 +64,7 @@ class HlsSegmentService:
# 每个分片请求都会起一个 FFmpeg;播放器本身就并发预取,多设备同看能把机器打满。
self._limit = max_concurrent or max(1, (os.cpu_count() or 4) // 2)
self._semaphore: asyncio.Semaphore | None = None
- self._plans: dict[tuple, list[tuple[float, float]]] = {}
+ self._plans: OrderedDict[tuple, list[tuple[float, float]]] = OrderedDict()
def _gate(self) -> asyncio.Semaphore:
if self._semaphore is None:
@@ -81,11 +83,12 @@ class HlsSegmentService:
key = (*self.fingerprint(source), self.segment_seconds, round(duration, 3))
cached = self._plans.get(key)
if cached is not None:
+ self._plans.move_to_end(key)
return cached or None
keyframes = keyframe_seconds(source)
result = segment_plan(keyframes, duration, self.segment_seconds) if keyframes else []
- if len(self._plans) > 256:
- self._plans.clear()
+ while len(self._plans) >= PLAN_CACHE_LIMIT:
+ self._plans.popitem(last=False)
self._plans[key] = result
return result or None
diff --git a/tests/test_segments.py b/tests/test_segments.py
index 4310adc20..721bafa3a 100644
--- a/tests/test_segments.py
+++ b/tests/test_segments.py
@@ -197,3 +197,42 @@ class SegmentCommandTests(unittest.TestCase):
# 决定性判据:终点随片段前移,而不是所有片段都停在第一段的末尾。
self.assertGreater(end, start)
self.assertAlmostEqual(end, round(index * 9.993, 3) + 9.993, places=2)
+
+
+class PlanCacheTests(unittest.TestCase):
+ """计划缓存一满就 clear() 等于没有缓存;改成 LRU 后热条目要能活下来。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ self.service = HlsSegmentService(
+ resolver=mock.Mock(ffmpeg=lambda: None), work_root=self.root / "cache")
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _source(self, number: int) -> Path:
+ path = self.root / f"clip{number}.mp4"
+ path.write_bytes(b"x")
+ return path
+
+ def _plan(self, number: int) -> None:
+ with mock.patch("peach.segments.keyframe_seconds", return_value=[0.0]):
+ self.service.plan(self._source(number), 60.0)
+
+ def _held_sources(self) -> set[str]:
+ return {key[0] for key in self.service._plans}
+
+ def test_cache_keeps_at_most_the_limit_and_evicts_the_oldest_access(self):
+ from peach.segments import PLAN_CACHE_LIMIT
+
+ for number in range(PLAN_CACHE_LIMIT):
+ self._plan(number)
+ self.assertEqual(len(self.service._plans), PLAN_CACHE_LIMIT)
+
+ # 命中一次让 0 号变成最近访问,再插入新条目:被逐出的必须是 1 号。
+ self._plan(0)
+ self._plan(PLAN_CACHE_LIMIT)
+ self.assertEqual(len(self.service._plans), PLAN_CACHE_LIMIT)
+ self.assertIn(str(self._source(0)), self._held_sources())
+ self.assertNotIn(str(self._source(1)), self._held_sources())