mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* Add a REST endpoint to start a library scan POST /api/tasks/scan queues a scan with the options of the `scan` socket event, so clients authenticating with a bearer or client token can start one without a Socket.IO session. It answers 202 with the queued job, 409 while a library scan is queued or running, and 503 when no worker listens on the scan queue. The enqueue path moves into queue_scan, shared with the socket handler. A short Redis lock now covers the in-flight check and the enqueue, so two requests landing on different web workers cannot both queue a library scan. The socket handler also answers scan:done_ko for an unknown scan type instead of raising. * Default a scan without apis to the enabled sources, lease the request lock A scan request that leaves out `apis` now uses every enabled metadata source, on the REST endpoint and the socket alike, as the scheduled scan and the watcher do. An explicit empty list still means no sources. The web UI always sends `apis`, so its scans are unchanged. redis_lock takes an optional lease_seconds, and the library scan request lock holds its key for 30s while waiters give up after 5s, so a slow holder cannot lose the lock to a waiter that then queues a second scan. * Narrow optional mock call args in the new scan tests * pr-ready step 2 (code-review): narrow the scan lock timeout handling to acquiring the lock Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * pr-ready step 3 (simplify): share the held-lock stub, read the task name off the queued job Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * pr-ready step 4 (review-polish): drop a test comment that recorded old behaviour Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Validate socket scan options with ScanPayload and list workers once per scan request The socket handler now parses its options with the same ScanPayload the REST endpoint uses, so an unknown key, scan type or metadata source answers scan:done_ko instead of falling back to a scan of everything. v1 callers that could send a null platform id now send a real one or none. queue_scan checks for a live scan worker itself, so the socket also refuses a scan no worker would pick up, and it lists the workers once for that check and the in-flight check. The blocking RQ calls run in a thread, off the event loop. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Rename useScanProviders' ScanPayload to ScanSourceOptions It shared its name with the generated ScanPayload request type while holding only the metadata source options. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
223 lines
7.0 KiB
Python
223 lines
7.0 KiB
Python
import asyncio
|
|
import threading
|
|
from typing import Any
|
|
from unittest.mock import MagicMock, PropertyMock, patch
|
|
|
|
import pytest
|
|
from rq import Worker
|
|
from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError
|
|
from rq.job import Job, JobStatus
|
|
|
|
from handler.redis_handler import (
|
|
RomMRedis,
|
|
async_cache,
|
|
cancel_job,
|
|
get_job_func_name,
|
|
get_job_kwargs,
|
|
get_job_status,
|
|
get_worker_current_job,
|
|
has_live_worker,
|
|
low_prio_queue,
|
|
redis_client,
|
|
redis_lock,
|
|
)
|
|
|
|
|
|
def make_job() -> MagicMock:
|
|
job = MagicMock(spec=Job)
|
|
job.id = "job-1"
|
|
return job
|
|
|
|
|
|
def unreadable(attribute: str) -> MagicMock:
|
|
"""A job whose `attribute` fails the way an undeserializable payload does.
|
|
|
|
Each mock gets its own type, so patching the property is instance-local.
|
|
"""
|
|
job = make_job()
|
|
setattr(type(job), attribute, PropertyMock(side_effect=DeserializationError))
|
|
return job
|
|
|
|
|
|
class TestGetJobFuncName:
|
|
def test_returns_the_recorded_name(self):
|
|
job = make_job()
|
|
job.func_name = "tasks.tasks.run_task_by_name"
|
|
|
|
assert get_job_func_name(job) == "tasks.tasks.run_task_by_name"
|
|
|
|
def test_falls_back_when_the_payload_cannot_be_read(self):
|
|
assert get_job_func_name(unreadable("func_name")) == ""
|
|
|
|
def test_returns_the_given_fallback(self):
|
|
job = unreadable("func_name")
|
|
|
|
assert get_job_func_name(job, fallback="unknown") == "unknown"
|
|
|
|
|
|
class TestGetJobKwargs:
|
|
def test_returns_the_enqueued_keyword_arguments(self):
|
|
job = make_job()
|
|
job.kwargs = {"platform_ids": [1]}
|
|
|
|
assert get_job_kwargs(job) == {"platform_ids": [1]}
|
|
|
|
def test_returns_empty_for_a_job_enqueued_without_keywords(self):
|
|
job = make_job()
|
|
job.kwargs = {}
|
|
|
|
assert get_job_kwargs(job) == {}
|
|
|
|
def test_returns_none_when_the_payload_cannot_be_read(self):
|
|
# None rather than empty: the caller has to tell "covers nothing" apart
|
|
# from "cannot be known".
|
|
assert get_job_kwargs(unreadable("kwargs")) is None
|
|
|
|
|
|
class TestGetJobStatus:
|
|
def test_returns_the_recorded_status(self):
|
|
job = make_job()
|
|
job.get_status.return_value = JobStatus.QUEUED
|
|
|
|
assert get_job_status(job) == JobStatus.QUEUED
|
|
|
|
def test_returns_none_once_the_job_hash_has_expired(self):
|
|
job = make_job()
|
|
job.get_status.side_effect = InvalidJobOperation
|
|
|
|
assert get_job_status(job) is None
|
|
|
|
|
|
class TestCancelJob:
|
|
def test_cancels_a_live_job(self):
|
|
job = make_job()
|
|
|
|
assert cancel_job(job) is True
|
|
job.cancel.assert_called_once()
|
|
|
|
def test_tolerates_a_job_cancelled_by_an_earlier_call(self):
|
|
# Stopping a scan twice reaches the running job again while it unwinds.
|
|
job = make_job()
|
|
job.cancel.side_effect = InvalidJobOperation
|
|
|
|
assert cancel_job(job) is False
|
|
|
|
|
|
class TestGetWorkerCurrentJob:
|
|
@staticmethod
|
|
def _worker(**kwargs) -> MagicMock:
|
|
worker = MagicMock(spec=Worker)
|
|
worker.get_current_job.configure_mock(**kwargs)
|
|
return worker
|
|
|
|
def test_returns_the_job_the_worker_is_holding(self):
|
|
job = make_job()
|
|
|
|
assert get_worker_current_job(self._worker(return_value=job)) is job
|
|
|
|
def test_returns_none_when_the_worker_is_idle(self):
|
|
assert get_worker_current_job(self._worker(return_value=None)) is None
|
|
|
|
def test_returns_none_when_the_job_outlived_by_its_worker_is_gone(self):
|
|
worker = self._worker(side_effect=NoSuchJobError)
|
|
|
|
assert get_worker_current_job(worker) is None
|
|
|
|
|
|
class TestHasLiveWorker:
|
|
@staticmethod
|
|
def _worker(state: str, death_date: str | None = None) -> MagicMock:
|
|
worker = MagicMock(spec=Worker)
|
|
worker.get_state.return_value = state
|
|
worker.death_date = death_date
|
|
return worker
|
|
|
|
@pytest.mark.parametrize(
|
|
("workers", "expected"),
|
|
[
|
|
([], False),
|
|
([("suspended", None)], False),
|
|
([("idle", "2026-09-16T10:00:00")], False),
|
|
([("suspended", None), ("idle", None)], True),
|
|
([("busy", None)], True),
|
|
],
|
|
ids=["none-registered", "suspended", "announced-dead", "one-live", "busy"],
|
|
)
|
|
def test_counts_only_workers_that_would_take_a_job(
|
|
self, workers: list[tuple[str, str | None]], expected: bool
|
|
):
|
|
registered = [self._worker(state, death) for state, death in workers]
|
|
|
|
with patch(
|
|
"handler.redis_handler.Worker.all", return_value=registered
|
|
) as mock_all:
|
|
assert has_live_worker(low_prio_queue) is expected
|
|
|
|
mock_all.assert_called_once_with(queue=low_prio_queue)
|
|
|
|
def test_reads_a_listing_the_caller_already_has(self):
|
|
elsewhere = self._worker("idle")
|
|
elsewhere.queue_names.return_value = ["other"]
|
|
listening = self._worker("busy")
|
|
listening.queue_names.return_value = [low_prio_queue.name]
|
|
|
|
with patch("handler.redis_handler.Worker.all") as mock_all:
|
|
assert has_live_worker(low_prio_queue, [elsewhere]) is False
|
|
assert has_live_worker(low_prio_queue, [elsewhere, listening]) is True
|
|
|
|
mock_all.assert_not_called()
|
|
|
|
|
|
class TestAsyncCacheUnderTests:
|
|
def test_concurrent_threads_and_loops_never_share_a_pool(self):
|
|
"""The TestClient's loop and a test's asyncio.run overlap across threads."""
|
|
|
|
async def running_loop_pool() -> Any:
|
|
return async_cache.connection_pool
|
|
|
|
pools: dict[str, Any] = {}
|
|
|
|
def other_thread() -> None:
|
|
pools["other thread, no loop"] = async_cache.connection_pool
|
|
pools["other thread, in a loop"] = asyncio.run(running_loop_pool())
|
|
|
|
thread = threading.Thread(target=other_thread)
|
|
thread.start()
|
|
thread.join()
|
|
pools["this thread, no loop"] = async_cache.connection_pool
|
|
pools["this thread, in a loop"] = asyncio.run(running_loop_pool())
|
|
|
|
assert len({id(pool) for pool in pools.values()}) == len(pools)
|
|
|
|
def test_every_client_reads_the_one_keyspace(self):
|
|
async def read() -> Any:
|
|
return await async_cache.get("per-loop")
|
|
|
|
asyncio.run(async_cache.set("per-loop", "1"))
|
|
value = asyncio.run(read())
|
|
|
|
assert value in ("1", b"1")
|
|
|
|
|
|
class TestRedisLock:
|
|
@pytest.mark.parametrize(
|
|
("lease_seconds", "expected_ttl"), [(None, 5), (30, 30)], ids=["wait", "lease"]
|
|
)
|
|
async def test_the_key_lives_for_the_lease(self, lease_seconds, expected_ttl):
|
|
async with redis_lock(
|
|
"test-lock", timeout_seconds=5, lease_seconds=lease_seconds
|
|
):
|
|
assert await async_cache.ttl("test-lock") == expected_ttl
|
|
|
|
assert not await async_cache.exists("test-lock")
|
|
|
|
|
|
def test_the_queue_client_skips_the_maintenance_notifications_probe():
|
|
assert not redis_client.connection_pool.maint_notifications_enabled()
|
|
|
|
|
|
def test_the_rq_cli_client_skips_the_maintenance_notifications_probe():
|
|
client = RomMRedis.from_url("redis://localhost:6379/0")
|
|
|
|
assert not client.connection_pool.maint_notifications_enabled()
|