Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(library): 读取新入库范围时持有写入方的同一把文件锁

longmeidao6c550533ba75
diff --git a/src/peach/library_new_assets.py b/src/peach/library_new_assets.py
index 69b5ddeb3..6cd7c4a1a 100644
--- a/src/peach/library_new_assets.py
+++ b/src/peach/library_new_assets.py
@@ -34,8 +34,18 @@ def _read(db):
return set(ids)
+def _lock(path):
+ return FileLock(str(path)+'.lock')
+
+
def pending(db):
- return _active_videos(db, sorted(_read(db)))
+ # `remember` 持锁原子替换;Windows 上替换瞬间的读取会撞上共享冲突,读也等同一把锁。
+ path = _path(db)
+ if not path.parent.is_dir():
+ return []
+ with _lock(path):
+ wanted = sorted(_read(db))
+ return _active_videos(db, wanted)
def _active_videos(db, wanted):
@@ -53,7 +63,7 @@ def _active_videos(db, wanted):
def remember(db, ids=(), *, completed=()):
path = _path(db)
path.parent.mkdir(parents=True,exist_ok=True)
- with FileLock(str(path)+'.lock'):
+ with _lock(path):
previous = _read(db)
updated = set(_active_videos(db, sorted(previous | set(ids)))) - set(completed)
if updated != previous or (updated and not path.exists()):
diff --git a/tests/test_processing_control.py b/tests/test_processing_control.py
index da5a95072..5b914d9c0 100644
--- a/tests/test_processing_control.py
+++ b/tests/test_processing_control.py
@@ -406,6 +406,36 @@ class ProcessingControlTests(unittest.TestCase):
'completed_metadata':['1:R:\\Media\\0.mp4']}),encoding='utf-8')
self.assertEqual(pending(self.db),[2,3])
+ def test_new_asset_range_is_read_under_the_writer_lock(self):
+ """`remember` 持锁原子替换文件;Windows 替换瞬间读会撞上共享冲突,所以读也要等同一把锁。"""
+ from filelock import FileLock
+ from peach.library_new_assets import pending
+ from peach.update_tasks import state_for
+ self.seed(3)
+ path=state_for(self.db).parent/'library-new-assets.json'
+ path.parent.mkdir(parents=True,exist_ok=True)
+ outcome={}
+
+ def read():
+ try:
+ outcome['ids']=pending(self.db)
+ except Exception as error:
+ outcome['error']=error
+ with FileLock(str(path)+'.lock'):
+ path.write_text('[1, 2',encoding='utf-8')
+ reader=threading.Thread(target=read)
+ reader.start()
+ reader.join(0.5)
+ self.assertTrue(reader.is_alive(),f'写入方持锁期间读到了半份文件:{outcome}')
+ path.write_text('[1, 2]',encoding='utf-8')
+ reader.join(5)
+ self.assertEqual(outcome,{'ids':[1,2]})
+
+ def test_new_asset_range_is_empty_before_any_state_exists(self):
+ from peach.library_new_assets import pending
+ self.seed(1)
+ self.assertEqual(pending(self.db),[])
+
def test_archiving_keeps_full_legacy_issues_and_export_rejects_changes(self):
import json
from peach.library_processing import state_path,_save