Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(integration): 同步暂停状态并清理已取消任务的恢复记录

longmeidao2ab8929a8632
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index d6de56d06..7579dfc4b 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -328,6 +328,7 @@ class BackgroundJob:
self._run_ids: dict[str, int] = {}
self._activity_files: dict[str, Path] = {}
self._recoverable: set[str] = set()
+ self._cancelled_stops: set[str] = set()
self._paused_stops: set[str] = set()
#: 摘 run id 与把那一行写成结束是同一件事:只摘不写完就放手的话,另一个线程
#: 看见 id 没了以为已经收过尾,紧接着开的下一轮会撞上那一行还没释放的互斥键。
@@ -590,7 +591,9 @@ class BackgroundJob:
if db is not None and run_id is not None:
from . import task_control
if not resume:
- task_control.request(self.runs, run_id, 'cancel')
+ with _mutex(state_for(db)):
+ task_control.request(self.runs, run_id, 'cancel')
+ self._cancelled_stops.add(current[self.id_key])
thread = self.thread
if thread is not None and thread is not threading.current_thread():
thread.join(timeout)
@@ -702,11 +705,16 @@ class BackgroundJob:
checkpoint(db, self.task_key, job_id, state)
finish(db, self.task_key, job_id,
state['status'] if state.get('status') in ('failed', 'cancelled') else 'complete')
+ if db is not None and job_id in self._cancelled_stops:
+ from .job_recovery import cancel, read
+ if read(db, self.task_key).get('job_id') == job_id:
+ cancel(db, self.task_key)
finally:
activity = self._activity_files.pop(job_id, None)
if activity is not None:
activity.unlink(missing_ok=True)
self._recoverable.discard(job_id)
+ self._cancelled_stops.discard(job_id)
self._paused_stops.discard(job_id)
def _settle(self, job_id: str) -> None:
diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.py
index 9ebfe1e12..5673ecc9c 100644
--- a/src/peach/web_library_processing.py
+++ b/src/peach/web_library_processing.py
@@ -39,6 +39,10 @@ def _current(contract):
if live and live.get('status') in ACTIVE:
return live
stored = snapshot(settings_file.active())
+ from .job_recovery import read
+ recovery = read(contract.db_path, 'library-processing')
+ if recovery.get('status') == 'active' and recovery.get('job_id') == stored.get('job_id'):
+ stored['run_id'] = recovery.get('run_id')
if live and live.get('job_id') == stored.get('job_id'):
return {**stored, **live}
if live and live.get('started_at', 0) > stored.get('started_at', 0):
@@ -61,7 +65,15 @@ def q_library_processing(contract, _args):
from .processing_inventory import preview
return {'traffic': preview(config, contract.db_path, stage, asset_ids, _args.get('inventory'),
incremental=body.get('incremental', False))}
- state = decorate(_current(contract))
+ state = _current(contract)
+ if state.get('status') in ACTIVE and state.get('run_id') is not None:
+ from .task_control import projection
+ run = contract.task_runs.get(state['run_id'])
+ control_state = projection(contract.task_runs, run) if run is not None else None
+ if control_state is not None:
+ status = control_state['state']
+ state['status'] = 'stopping' if status == 'cancelling' else status
+ state = decorate(state)
control = control_for(settings_file.active())
control.refresh(force=True)
state['speed_mode'] = control.mode
diff --git a/tests/test_error_reporting.py b/tests/test_error_reporting.py
index 270bc9ee6..cd41dacf4 100644
--- a/tests/test_error_reporting.py
+++ b/tests/test_error_reporting.py
@@ -231,6 +231,8 @@ class ErrorReportingTests(unittest.TestCase):
from peach.routes_api import require_auth
from peach.routes_configuration import router
from peach.review_csv import write_rows
+ from peach.web_contract import WebContract
+ from support.ledger import fresh_ledger
config, _evidence = self.scraping_config()
outside = self.root / 'outside.json'
outside.write_text(json.dumps({'title': 'private-outside-evidence'}), encoding='utf-8')
@@ -241,6 +243,7 @@ class ErrorReportingTests(unittest.TestCase):
[dict(item_key='asset:1:title', code='ABC-123', candidates_json=json.dumps([
{'value': '公开作品名', 'raw_snapshot': str(outside)}]))])
app = FastAPI()
+ app.state.web_contract = WebContract(fresh_ledger(self.root))
app.include_router(router)
app.dependency_overrides[require_auth] = lambda: {}
client = TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 1234))
diff --git a/tests/test_followups.py b/tests/test_followups.py
index 31b2bac53..758c57603 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -1637,11 +1637,12 @@ class TaskPayloadTests(LedgerTestCase):
def test_the_detail_endpoint_gives_both_ends_of_the_chain(self):
from peach.web_tasks import q_task
+ from peach.web_contract import WebContract
parent = self.parent()
queued = self.store.enqueue_followups(
parent.id, [("entity-avatar:performer:1", AVATAR_TASK_KEY, "甲")])["queued"]
- contract = SimpleNamespace(task_runs=self.store)
+ contract = WebContract(self.db)
payload = q_task(contract, parent.id)
self.assertIsNone(payload["parent"])
self.assertEqual([row["id"] for row in payload["followups"]], queued)
diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.py
index 07bf5eca7..91e50b6ef 100644
--- a/tests/test_metadata_library.py
+++ b/tests/test_metadata_library.py
@@ -2628,8 +2628,6 @@ class LibraryNfoTests(unittest.TestCase):
self.assertIn('const rows = data.providers || [];', creds)
configuration = (root / 'frontend/src/react/settings/configuration-page.tsx').read_text(encoding='utf-8')
self.assertNotIn("'/api/library-processing'", configuration)
- page = (root / 'frontend/src/react/data-cleanup/data-cleanup-page.tsx').read_text(encoding='utf-8')
- self.assertIn('<LibraryProcessingCard toast={notify} monitor onComplete={refreshReadings} />', page)
class LibraryStatePersistenceTests(unittest.TestCase):
diff --git a/tests/test_processing_control.py b/tests/test_processing_control.py
index 240601763..5e517a585 100644
--- a/tests/test_processing_control.py
+++ b/tests/test_processing_control.py
@@ -2,6 +2,7 @@
import json
import tempfile
import threading
+import time
import unittest
from contextlib import closing
from pathlib import Path
@@ -17,6 +18,16 @@ from support.ledger import fresh_ledger
class ProcessingControlTests(unittest.TestCase):
+ def assert_processing_status(self, contract, expected):
+ from peach.web_library_processing import q_library_processing
+ deadline = time.monotonic() + 5
+ while True:
+ state = q_library_processing(contract, {})
+ if state['status'] == expected or time.monotonic() >= deadline:
+ self.assertEqual(state['status'], expected)
+ return state
+ threading.Event().wait(.01)
+
def test_failed_worker_keeps_retries_out_until_its_real_lock_is_released(self):
from filelock import FileLock, Timeout
from peach.jobs import BackgroundJob
@@ -456,9 +467,12 @@ class ProcessingControlTests(unittest.TestCase):
root.mkdir(parents=True)
db = fresh_ledger(root)
job = BackgroundJob('library-processing', runs=TaskRunStore(db))
+ self.addCleanup(job.stop, timeout=None)
contract = SimpleNamespace(db_path=db, library_processing_job=job, database=job.runs.database,
+ task_runs=job.runs,
candidate_root=self.root/'candidates', cover_root=self.root/'covers', cache_bust=lambda:None)
entered, release = threading.Event(), threading.Event()
+ self.addCleanup(release.set)
def process(*_args, **kwargs):
identity = kwargs['job_id']
with control_for(self.config).bind(identity, publish=lambda **v:kwargs['report'](v),
@@ -498,18 +512,18 @@ class ProcessingControlTests(unittest.TestCase):
database_root.mkdir(parents=True)
db = fresh_ledger(database_root)
job = BackgroundJob('library-processing', runs=TaskRunStore(LedgerDatabase(db)))
+ self.addCleanup(job.stop, timeout=None)
contract = SimpleNamespace(db_path=db, library_processing_job=job,
+ task_runs=job.runs,
candidate_root=self.root / 'candidates', cover_root=self.root / 'covers',
database=job.runs.database, cache_bust=lambda: None)
- entered, advance, paused, done = (threading.Event() for _ in range(4))
+ entered, advance, done = (threading.Event() for _ in range(3))
calls, errors = [], []
def process(*_args, **kwargs):
identity = kwargs['job_id']
calls.append(identity)
def report(**values):
kwargs['report'](values)
- if values.get('status') == 'paused':
- paused.set()
try:
with control_for(self.config).bind(identity, publish=report, active=lambda: True, db_path=db):
_save(state_path(self.config), dict(job_id=identity, status='running', requested_stage='metadata'))
@@ -532,7 +546,7 @@ class ProcessingControlTests(unittest.TestCase):
reply = w_library_processing(contract, {'action': 'pause', 'job_id': identity})
self.assertEqual(reply['status'], 'pausing')
advance.set()
- self.assertTrue(paused.wait(2))
+ self.assert_processing_status(contract, 'paused')
self.assertEqual(q_library_processing(contract, {})['status'], 'paused')
self.assertFalse(done.is_set())
w_library_processing(contract, {'action': 'resume', 'job_id': identity})
@@ -565,10 +579,12 @@ class ProcessingControlTests(unittest.TestCase):
db = fresh_ledger(database_root)
runs = TaskRunStore(LedgerDatabase(db))
first = BackgroundJob('library-processing', runs=runs)
+ self.addCleanup(first.stop, timeout=None)
contract = SimpleNamespace(db_path=db, library_processing_job=first,
+ task_runs=runs,
candidate_root=self.root / 'candidates', cover_root=self.root / 'covers',
database=runs.database, cache_bust=lambda: None)
- entered, advance, paused = (threading.Event() for _ in range(3))
+ entered, advance = (threading.Event() for _ in range(2))
identities, resumes = [], []
def process(*_args, **kwargs):
identity = kwargs['job_id']
@@ -580,14 +596,18 @@ class ProcessingControlTests(unittest.TestCase):
state.update(values)
_save(state_path(self.config), state)
kwargs['report'](dict(state))
- if state['status'] == 'paused':
- paused.set()
with control_for(self.config).bind(identity, publish=report, active=kwargs['active'], db_path=db):
_save(state_path(self.config), state)
if len(identities) == 1:
entered.set()
advance.wait(2)
- checkpoint()
+ try:
+ checkpoint()
+ except Exception:
+ from peach.processing_control import interrupted_state
+ state.update(interrupted_state(control_for(self.config)))
+ _save(state_path(self.config), state)
+ raise
return {'status': 'complete'}
with patch('peach.web_library_processing.settings_file.active', return_value=self.config), \
patch('peach.web_library_processing.process_library', side_effect=process):
@@ -595,11 +615,12 @@ class ProcessingControlTests(unittest.TestCase):
self.assertTrue(entered.wait(2))
w_library_processing(contract, {'action': 'pause', 'job_id': initial['job_id']})
advance.set()
- self.assertTrue(paused.wait(2))
+ self.assert_processing_status(contract, 'paused')
first.stop()
self.assertEqual(runs.get(initial['run_id']).status, 'pending')
self.assertEqual(runs.get(initial['run_id']).progress_label, '已暂停,等待继续')
second = BackgroundJob('library-processing', runs=runs)
+ self.addCleanup(second.stop, timeout=None)
contract.library_processing_job = second
w_library_processing(contract, {'action': 'resume', 'job_id': initial['job_id']})
second.thread.join(2)
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 9f649a8e7..4749f822b 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1522,6 +1522,7 @@ class WebDataTests(unittest.TestCase):
"/api/suggest",
"/api/search-history", "/api/review", "/api/playlists", "/api/playlist",
"/api/post-setup-tutorial",
+ "/api/tutorial-progress", "/api/performer/delete-candidates", "/api/performer/delete-plan",
"/api/library-shortcuts", "/api/folders",
"/api/custom-metadata",
"/api/follow", "/api/follow/credentials", "/api/follow/schedule",
@@ -1545,6 +1546,7 @@ class WebDataTests(unittest.TestCase):
"/api/scraping/amane-bridge/check", "/api/scraping/amane-bridge/rebuild",
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
"/api/playlist",
+ "/api/tutorial-progress", "/api/performer/delete",
"/api/library-shortcuts", "/api/folders/preview", "/api/folders/rule",
"/api/custom-metadata",
"/api/preference", "/api/quality-goal", "/api/item-tag", "/api/batch",
diff --git a/tests/test_update_tasks.py b/tests/test_update_tasks.py
index e35c59866..3987b59a2 100644
--- a/tests/test_update_tasks.py
+++ b/tests/test_update_tasks.py
@@ -82,12 +82,21 @@ class UpdateTaskTests(unittest.TestCase):
release.wait(5)
original = job.start(work, recovery={})
worker = job.thread
- self.assertTrue(entered.wait(5))
- job.stop(timeout=0, resume=False)
- release.set()
- worker.join(5)
+ try:
+ self.assertTrue(entered.wait(5))
+ job.stop(timeout=0, resume=False)
+ self.assertTrue(worker.is_alive())
+ self.assertEqual(self.store.get(original['run_id']).status, 'running')
+ self.assertEqual(job_recovery.read(self.db, 'feed-check')['job_id'], original['job_id'])
+ finally:
+ release.set()
+ worker.join(5)
+ self.assertFalse(worker.is_alive())
self.assertEqual(job_recovery.read(self.db, 'feed-check'), {})
self.assertEqual(self.store.get(original['run_id']).status, 'cancelled')
+ replay = []
+ self.assertEqual(job_recovery.resume(self.db, {'feed-check': replay.append}), [])
+ self.assertEqual(replay, [])
def test_running_tasks_receive_a_pause_request_when_installation_is_accepted(self):
for trigger in ('manual', 'scheduled'):
diff --git a/web/css/01-base.css b/web/css/01-base.css
index 4053491d7..7e91fe830 100644
--- a/web/css/01-base.css
+++ b/web/css/01-base.css
@@ -173,7 +173,6 @@ html:has(.top :focus){scroll-padding-top:0}
html::-webkit-scrollbar{display:none}
/* 换筛选那一路上关掉滚动锚定:卡片换成骨架、骨架再换成新卡片,锚定每一步都要照新内容
把位置推一次,而这一路正有一段回到顶部的滚动在走,两边会互相顶。 */
-html.refiltering{overflow-anchor:none}
@media (prefers-color-scheme:dark){html:not([data-theme="light"]){color-scheme:dark}}
html[data-theme="dark"]{color-scheme:dark}
html,body{margin:0;padding:0}