Generic background worker (phase 0, step 2)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Failing after 38s
CI / test (push) Successful in 46s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

scrobbler/worker.py runs tasks that modules register: queue tasks
(called while they report work) and periodic tasks. A failing task is
logged, counted, rolled back and doesn't stop the others. Imports are
now just a registered task plus a periodic stall check.

- `flask worker` replaces `flask imports worker` (kept as an alias);
  compose uses the new command
- scrobbler_worker_tasks_total{task,outcome} and a Worker tasks panel
  on the Usage dashboard
- WORKER_METRICS_PORT (IMPORT_WORKER_METRICS_PORT still honoured)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 19:57:25 +01:00
1 parent 59ff1bdfa0
commit 098eab025f
13 files changed
+292 -42

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
import time
from contextlib import contextmanager
from scrobbler import events
from scrobbler import events, worker
from scrobbler.services import imports, scrobbles
from scrobbler.services.scrobbles import TrackInput
@@ -62,7 +62,7 @@ def test_imports_announce_stored_plays_and_completion(app, user):
csv = f"Artist,,One,{when}\nArtist,,One,{when}\nArtist,,Two,{when}\n"
job = imports.create_file_import(user, "export.csv", csv.encode())
with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished:
imports.run_worker(once=True)
worker.run(once=True)
[(_, kwargs)] = stored
assert kwargs["source"] == "import"
assert sorted(s.track for s in kwargs["scrobbles"]) == ["One", "Two"] # the repeat once
+2 -1
View File
@@ -6,6 +6,7 @@ from datetime import UTC, datetime, timedelta
import pytest
from werkzeug.serving import make_server
from scrobbler import worker
from scrobbler.extensions import db
from scrobbler.models import ImportJob, Scrobble
from scrobbler.services import imports
@@ -29,7 +30,7 @@ def stored(user):
def run_all():
imports.run_worker(once=True)
worker.run(once=True)
db.session.expire_all()
+2 -2
View File
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
import pytest
from scrobbler.services import imports
from scrobbler import worker
def csv_bytes(n=3) -> bytes:
@@ -45,7 +45,7 @@ def test_upload_then_follow_progress(client, auth):
job = response.get_json()
assert (job["source"], job["status"], job["filename"]) == ("csv", "pending", "export.csv")
imports.run_worker(once=True)
worker.run(once=True)
done = client.get(f"/api/v1/imports/{job['id']}", headers=auth).get_json()
assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3)
assert client.get("/api/v1/me/summary", headers=auth).get_json()["scrobbles"] == 3
+66
View File
@@ -0,0 +1,66 @@
import pytest
from scrobbler import worker
@pytest.fixture
def tasks(app):
"""An empty task registry for the test, restored afterwards."""
saved = dict(worker._tasks)
worker._tasks.clear()
yield worker
worker._tasks.clear()
worker._tasks.update(saved)
def test_imports_are_registered_by_the_app(app):
assert {"imports", "imports.requeue_stalled"} <= set(worker.registered())
def test_queue_tasks_run_until_there_is_no_work(tasks, metric_delta):
work = [3]
def drain():
if work[0] == 0:
return False
work[0] -= 1
return True
worked = metric_delta("scrobbler_worker_tasks_total", task="drain", outcome="worked")
tasks.register_task("drain", drain)
tasks.run(once=True)
assert work == [0]
assert worked.delta == 3
def test_periodic_tasks_keep_their_interval(tasks):
calls = []
tasks.register_periodic("tick", 3600, lambda: calls.append(1))
busy = [2]
tasks.register_task("busy", lambda: busy.__setitem__(0, busy[0] - 1) or busy[0] >= 0)
tasks.run(once=True) # several passes while "busy" has work
assert calls == [1] # ran at start, then not again within the hour
def test_a_failing_task_does_not_stop_the_others(tasks, metric_delta):
done = []
def broken():
raise RuntimeError("bug")
errors = metric_delta("scrobbler_worker_tasks_total", task="broken", outcome="error")
tasks.register_task("broken", broken)
tasks.register_task("fine", lambda: done.append(1) and False)
tasks.run(once=True)
assert done == [1]
assert errors.delta == 1
def test_worker_cli_lists_and_runs_tasks(app, tasks):
ran = []
tasks.register_task("cli-test", lambda: ran.append(1) and False)
result = app.test_cli_runner().invoke(args=["worker", "--once", "--no-metrics"])
assert result.exit_code == 0, result.output
assert ran == [1]
alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"])
assert alias.exit_code == 0, alias.output