Skip to content

The only downloader you need. 下载器的集大成者。

refactor(runner): CoroutineRunner 去 Qt,注入 dispatcher 和 isAlive

XiaoYouChR1785504722a9
diff --git a/app/services/coroutine_runner.py b/app/services/coroutine_runner.py
index 2574ee61..3054b4fd 100644
--- a/app/services/coroutine_runner.py
+++ b/app/services/coroutine_runner.py
@@ -1,35 +1,38 @@
from __future__ import annotations
import asyncio
-from typing import Callable
+from threading import Thread
+from typing import Any, Callable
from uuid import uuid4
-from PySide6.QtCore import QObject, QThread, QTimer
-from PySide6.QtWidgets import QApplication
-from shiboken6 import isValid
from loguru import logger
-class CoroutineRunner(QThread):
+class CoroutineRunner:
- def __init__(self, parent=None):
- super().__init__(parent)
+ def __init__(self, dispatcher: Callable[[Callable], None], isAlive: Callable[[Any], bool] | None = None):
+ self._dispatcher = dispatcher
+ self._isAlive = isAlive
self._loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
+ self._thread = Thread(target=self._run, daemon=True)
self._pending: dict[str, tuple] = {}
self._running: dict[str, asyncio.Task] = {}
- def run(self):
+ def _run(self):
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
self._loop.close()
+ def start(self):
+ self._thread.start()
+
def submit(
self,
work,
done: Callable = None,
failed: Callable = None,
*args,
- owner: QObject = None,
+ owner=None,
**kwargs,
) -> str:
workId = f"wrk_{uuid4().hex}"
@@ -87,18 +90,15 @@ class CoroutineRunner(QThread):
except Exception as e:
logger.opt(exception=e).error("callback failed")
- app = QApplication.instance()
- if app is not None:
- QTimer.singleShot(0, app, wrapper)
- else:
- wrapper()
+ self._dispatcher(wrapper)
- def _guard(self, owner: QObject, callback: Callable) -> Callable | None:
+ def _guard(self, owner, callback: Callable) -> Callable | None:
if callback is None:
return None
+ isAlive = self._isAlive
def guarded(*args, **kwargs):
- if isValid(owner):
+ if isAlive is None or isAlive(owner):
callback(*args, **kwargs)
return guarded
@@ -110,4 +110,3 @@ class CoroutineRunner(QThread):
self._loop.call_soon_threadsafe(self._loop.stop)
self._pending.clear()
self._running.clear()
-
diff --git a/app/startup.py b/app/startup.py
index 8cf42a1a..bd81e89d 100644
--- a/app/startup.py
+++ b/app/startup.py
@@ -24,14 +24,15 @@ def loadEngine(application):
from app.services.coroutine_runner import CoroutineRunner
from app.services.speed_meter import SpeedMeter
- from PySide6.QtCore import QResource
+ from PySide6.QtCore import QResource, QTimer
+ from shiboken6 import isValid
from app.config.paths import executableDir
QResource.registerResource(str(executableDir / "app" / "assets" / "resources.rcc"))
loadTranslators(application)
- coroutineRunner = CoroutineRunner(parent=application)
+ coroutineRunner = CoroutineRunner(lambda fn: QTimer.singleShot(0, application, fn), isAlive=isValid)
categoryService = CategoryService()
speedMeter = SpeedMeter(coroutineRunner)
diff --git a/tests/test_aria2_rpc_e2e.py b/tests/test_aria2_rpc_e2e.py
index 8531bc61..5bb6729b 100644
--- a/tests/test_aria2_rpc_e2e.py
+++ b/tests/test_aria2_rpc_e2e.py
@@ -39,11 +39,14 @@ def _rpcRequest(port: int, method: str, params: list | None = None, rpcId: int =
@pytest.fixture
def runner(qapp):
- cr = CoroutineRunner(parent=qapp)
+ from PySide6.QtCore import QTimer
+ from shiboken6 import isValid
+
+ dispatcher = lambda fn: QTimer.singleShot(0, qapp, fn)
+ cr = CoroutineRunner(dispatcher, isAlive=isValid)
cr.start()
yield cr
cr.stop()
- cr.wait(3000)
@pytest.fixture
diff --git a/tests/test_browser_service_e2e.py b/tests/test_browser_service_e2e.py
index e15bcf75..5a507ff3 100644
--- a/tests/test_browser_service_e2e.py
+++ b/tests/test_browser_service_e2e.py
@@ -49,11 +49,14 @@ def processEventsUntil(qapp, predicate, timeout=5.0):
@pytest.fixture()
def runner(qapp):
- cr = CoroutineRunner(parent=qapp)
+ from PySide6.QtCore import QTimer
+ from shiboken6 import isValid
+
+ dispatcher = lambda fn: QTimer.singleShot(0, qapp, fn)
+ cr = CoroutineRunner(dispatcher, isAlive=isValid)
cr.start()
yield cr
cr.stop()
- cr.wait(2000)
@pytest.fixture()
diff --git a/tests/test_task_service.py b/tests/test_task_service.py
index 2ffe8478..5647bd7a 100644
--- a/tests/test_task_service.py
+++ b/tests/test_task_service.py
@@ -70,6 +70,15 @@ class StubSpeedMeter:
pass
+class StubFileWatcher:
+ class _Signal:
+ def connect(self, _): pass
+ fileChanged = _Signal()
+
+ def addPath(self, _): pass
+ def removePath(self, _): pass
+
+
# ── Fixtures ──
@@ -83,7 +92,7 @@ def service(qapp, monkeypatch, tmp_path):
runner = StubCoroutineRunner()
category = StubCategoryService()
speed = StubSpeedMeter()
- svc = TaskService(runner, category, speed)
+ svc = TaskService(runner, category, speed, StubFileWatcher())
return svc, runner