diff --git a/backend/handler/database/base_handler.py b/backend/handler/database/base_handler.py index 11bd37861..f310d5066 100644 --- a/backend/handler/database/base_handler.py +++ b/backend/handler/database/base_handler.py @@ -7,6 +7,7 @@ from sqlalchemy.orm import sessionmaker from config import DB_POOL_RECYCLE_SECONDS, DEV_SQL_ECHO from config.config_manager import ConfigManager +from models import load_all_models # A ping on a socket the server already closed blocks the worker until TCP gives # up, so `pool_pre_ping` alone is not enough. @@ -59,3 +60,8 @@ def affected_rows(result: Result[Any]) -> int: """How many rows an UPDATE or DELETE run through `Session.execute` matched.""" # Session.execute is typed to return Result, but DML gets a CursorResult. return cast(CursorResult[Any], result).rowcount + + +# A process may load one model, whose relationships name others by string, and +# the mappers configure only once every one of them is loaded. +load_all_models() diff --git a/backend/handler/recommendation/builder.py b/backend/handler/recommendation/builder.py index dfa76c329..ff30a75e2 100644 --- a/backend/handler/recommendation/builder.py +++ b/backend/handler/recommendation/builder.py @@ -18,6 +18,7 @@ from typing import Any, Final from handler.database import db_recommendation_handler from handler.database.recommendations_handler import RomFeatureRow from logger.logger import log +from tasks.registry import enqueue_task from .feed import invalidate_all_cached_feeds from .scoring import ( @@ -583,10 +584,6 @@ def top_up_similarity(rom_ids: Collection[int]) -> None: return if len(unique_ids) > MAX_TOP_UP_ROMS: - # Deferred: the task registry imports every task module, and one of - # them imports this package. - from tasks.registry import enqueue_task - log.info( f"{len(unique_ids)} ROMs scanned, more than a recommendations top-up " "is worth; queueing a full rebuild instead" diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 1f2be9bc9..ce4e7e924 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -1,10 +1,10 @@ """The catalog of tasks, kept free of task code so scheduling or listing them imports none.""" -import importlib -from typing import Any, Final +from typing import Any, Final, cast -from rq.job import Job +from rq.job import Callback, Job from rq.queue import Queue +from rq.utils import import_attribute from config import ( AUDIT_LOG_RETENTION_DAYS, @@ -271,9 +271,7 @@ def get_task(name: str) -> Task | None: spec = get_task_spec(name) if spec is None: return None - module, _, attribute = spec.implementation.rpartition(".") - task: Task = getattr(importlib.import_module(module), attribute) - return task + return cast(Task, import_attribute(spec.implementation)) def enqueue_task( @@ -327,8 +325,6 @@ def enqueue_scheduled_scan(name: str) -> str: Returns: The id of the enqueued scan job. """ - # Imported here because the cron process registers this function and must - # not load the scan stack to do it. - from endpoints.sockets.scan import report_scan_failure - - return enqueue_task(name, queue=scan_queue, on_failure=report_scan_failure).id + # By path, so the dispatch job doesn't load the scan stack to reference it. + on_failure = Callback("endpoints.sockets.scan.report_scan_failure") + return enqueue_task(name, queue=scan_queue, on_failure=on_failure).id diff --git a/backend/tasks/sync_push_pull_task.py b/backend/tasks/sync_push_pull_task.py index d1ee85d30..6381083c8 100644 --- a/backend/tasks/sync_push_pull_task.py +++ b/backend/tasks/sync_push_pull_task.py @@ -11,7 +11,6 @@ import asyncssh from anyio import Path as AnyioPath from anyio import open_file -from config import ENABLE_SYNC_PUSH_PULL from handler.database import ( db_deleted_asset_handler, db_device_handler, @@ -37,7 +36,7 @@ async def run_push_pull_sync( force: bool = False, ) -> dict[str, Any]: """Execute push-pull sync for one or all push_pull devices.""" - if not ENABLE_SYNC_PUSH_PULL and not force: + if not SYNC_PUSH_PULL_SPEC.enabled and not force: log.info("Push-pull sync not enabled, skipping") return {"status": "disabled"} diff --git a/backend/tasks/tasks.py b/backend/tasks/tasks.py index d4459a419..8b0b8bde1 100644 --- a/backend/tasks/tasks.py +++ b/backend/tasks/tasks.py @@ -39,12 +39,8 @@ async def run_task_by_name( Whatever the task returns. """ # Imported here because the task modules the registry resolves import this one. - from models import load_all_models from tasks.registry import get_task - # A task module may load a model whose relationships name models it doesn't - # import, and the mappers configure only once every one of them is loaded. - load_all_models() task = get_task(name) if task is None: raise TaskNotFoundException(name) diff --git a/backend/tests/tasks/test_registry.py b/backend/tests/tasks/test_registry.py index 49ef4a459..ab3cee9cc 100644 --- a/backend/tests/tasks/test_registry.py +++ b/backend/tests/tasks/test_registry.py @@ -1,4 +1,5 @@ import pytest +from rq.utils import import_attribute from config import TASK_RESULT_TTL from endpoints.sockets.scan import report_scan_failure @@ -98,7 +99,7 @@ class TestEnqueueScheduledScan: args, kwargs = scan_queue.enqueue.call_args assert args[0] is run_task_by_name assert kwargs["kwargs"]["name"] == "scan_library" - assert kwargs["on_failure"] is report_scan_failure + assert import_attribute(kwargs["on_failure"].func) is report_scan_failure def test_the_scan_carries_its_own_timeout(self, scan_queue): # The dispatch itself runs on the ordinary task timeout, so the scan diff --git a/backend/tests/tasks/test_sync_push_pull.py b/backend/tests/tasks/test_sync_push_pull.py index f98daa45d..9c56ee29d 100644 --- a/backend/tests/tasks/test_sync_push_pull.py +++ b/backend/tests/tasks/test_sync_push_pull.py @@ -1,5 +1,6 @@ """Tests for SyncPushPullTask initialization and configuration.""" +from dataclasses import replace from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch @@ -18,6 +19,7 @@ from models.device import Device, SyncMode from models.platform import Platform from models.rom import Rom from models.user import User +from tasks.registry import SYNC_PUSH_PULL_SPEC from tasks.sync_push_pull_task import ( SyncPushPullTask, _process_remote_save, @@ -49,14 +51,20 @@ class TestSyncPushPullTaskInit: class TestRunPushPullSync: - @patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", False) + @patch( + "tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC", + replace(SYNC_PUSH_PULL_SPEC, enabled=False), + ) async def test_run_disabled_returns_disabled(self): from tasks.sync_push_pull_task import run_push_pull_sync result = await run_push_pull_sync() assert result["status"] == "disabled" - @patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", True) + @patch( + "tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC", + replace(SYNC_PUSH_PULL_SPEC, enabled=True), + ) @patch("tasks.sync_push_pull_task.db_device_handler") async def test_run_no_devices(self, mock_device_handler): from tasks.sync_push_pull_task import run_push_pull_sync @@ -66,7 +74,10 @@ class TestRunPushPullSync: result = await run_push_pull_sync() assert result["status"] == "no_devices" - @patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", True) + @patch( + "tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC", + replace(SYNC_PUSH_PULL_SPEC, enabled=True), + ) @patch("tasks.sync_push_pull_task.db_device_handler") async def test_run_device_not_found(self, mock_device_handler): from tasks.sync_push_pull_task import run_push_pull_sync @@ -77,7 +88,10 @@ class TestRunPushPullSync: assert result["status"] == "error" assert "not found" in result["message"] - @patch("tasks.sync_push_pull_task.ENABLE_SYNC_PUSH_PULL", False) + @patch( + "tasks.sync_push_pull_task.SYNC_PUSH_PULL_SPEC", + replace(SYNC_PUSH_PULL_SPEC, enabled=False), + ) async def test_run_force_override(self): from tasks.sync_push_pull_task import run_push_pull_sync