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

+3 -3
View File
@@ -12,7 +12,7 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
- **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages. - **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages.
- **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served. - **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served.
- **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`. - **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`.
- **Import worker**: `flask imports worker` imports Last.fm history in the background, from export files or straight from Last.fm. - **Worker**: `flask worker` runs background work, such as importing Last.fm history from export files or straight from Last.fm.
- **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules. - **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules.
## Run it ## Run it
@@ -47,7 +47,7 @@ The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | | `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) |
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | | `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | | `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port (`IMPORT_WORKER_METRICS_PORT` still works) |
| `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP | | `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP |
In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`. In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`.
@@ -100,7 +100,7 @@ uv sync
uv run flask --app scrobbler db upgrade uv run flask --app scrobbler db upgrade
uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS)
python -m http.server 8080 -d frontend # UI python -m http.server 8080 -d frontend # UI
uv run flask --app scrobbler imports worker # process imports uv run flask --app scrobbler worker # background work (imports, …)
uv run pytest # needs TEST_DATABASE_URL (see .env.example) uv run pytest # needs TEST_DATABASE_URL (see .env.example)
uv run ruff check && uv run ruff format --check uv run ruff check && uv run ruff format --check
``` ```
+65 -4
View File
@@ -572,7 +572,7 @@
}, },
{ {
"type": "row", "type": "row",
"title": "Imports", "title": "Background work",
"id": 13, "id": 13,
"collapsed": false, "collapsed": false,
"gridPos": { "gridPos": {
@@ -878,6 +878,67 @@
"h": 8 "h": 8
} }
}, },
{
"type": "timeseries",
"title": "Worker tasks",
"description": "Runs of each background task that did work, and failures. A task that keeps failing is logged by the worker.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"worked\"}[$__rate_interval]))",
"legendFormat": "{{task}}",
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"error\"}[$__rate_interval]))",
"legendFormat": "{{task}} errors",
"refId": "B"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 70,
"showPoints": "never",
"spanNulls": true,
"drawStyle": "bars"
},
"min": 0
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"id": 19,
"gridPos": {
"x": 12,
"y": 38,
"w": 12,
"h": 8
}
},
{ {
"type": "timeseries", "type": "timeseries",
"title": "Import duration (p95)", "title": "Import duration (p95)",
@@ -921,10 +982,10 @@
"sort": "desc" "sort": "desc"
} }
}, },
"id": 19, "id": 20,
"gridPos": { "gridPos": {
"x": 12, "x": 0,
"y": 38, "y": 46,
"w": 12, "w": 12,
"h": 8 "h": 8
} }
+2 -2
View File
@@ -42,13 +42,13 @@ services:
db: db:
condition: service_healthy condition: service_healthy
# Processes history imports (uploaded exports and pulls from Last.fm). # Background work: history imports, and tasks registered by optional modules.
worker: worker:
image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local} image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local}
build: build:
context: . context: .
dockerfile: docker/api.Dockerfile dockerfile: docker/api.Dockerfile
command: ["flask", "--app", "scrobbler", "imports", "worker"] command: ["flask", "--app", "scrobbler", "worker"]
environment: environment:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
SECRET_KEY: ${SECRET_KEY:-change-me} SECRET_KEY: ${SECRET_KEY:-change-me}
+4 -1
View File
@@ -37,9 +37,12 @@ def create_app(config_object=None):
max_age=600, max_age=600,
) )
from scrobbler.cli import imports_cli from scrobbler.cli import imports_cli, worker_command
from scrobbler.services import imports as import_service
app.cli.add_command(worker_command)
app.cli.add_command(imports_cli) app.cli.add_command(imports_cli)
import_service.register_worker_tasks()
from scrobbler.metrics import db as db_metrics from scrobbler.metrics import db as db_metrics
+36 -14
View File
@@ -2,22 +2,44 @@ import logging
import click import click
from flask import current_app from flask import current_app
from flask.cli import AppGroup from flask.cli import AppGroup, with_appcontext
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
from scrobbler import worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if serve_metrics:
from scrobbler.metrics.server import start_metrics_server
start_metrics_server(current_app.config["WORKER_METRICS_PORT"])
logging.getLogger(__name__).info("worker tasks: %s", ", ".join(worker.registered()))
worker.run(poll_seconds=poll, once=once)
def _worker_options(fn):
fn = click.option(
"--metrics/--no-metrics", "serve_metrics", default=True, help="Serve Prometheus metrics."
)(fn)
fn = click.option(
"--poll", default=2.0, show_default=True, help="Seconds between checks when idle."
)(fn)
return click.option("--once", is_flag=True, help="Do all waiting work, then exit.")(fn)
@click.command("worker")
@_worker_options
@with_appcontext
def worker_command(once: bool, poll: float, serve_metrics: bool) -> None:
"""Run background work: imports, and tasks registered by optional modules."""
_run_worker(once, poll, serve_metrics)
imports_cli = AppGroup("imports", help="History imports.") imports_cli = AppGroup("imports", help="History imports.")
@imports_cli.command("worker") @imports_cli.command("worker")
@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.") @_worker_options
@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.") def imports_worker(once: bool, poll: float, serve_metrics: bool) -> None:
@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.") """Alias for `flask worker` (kept for existing deployments)."""
def worker(once: bool, poll: float, metrics: bool) -> None: _run_worker(once, poll, serve_metrics)
"""Process import jobs: uploaded Last.fm exports and pulls from Last.fm."""
from scrobbler.services.imports import run_worker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
if metrics:
from scrobbler.metrics.server import start_metrics_server
start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"])
run_worker(poll_seconds=poll, once=once)
+4 -1
View File
@@ -56,7 +56,10 @@ class Config:
LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25")) LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25"))
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024))) IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024)))
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101")) # IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured.
WORKER_METRICS_PORT = int(
os.environ.get("WORKER_METRICS_PORT", os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101"))
)
# Last.fm behaviour # Last.fm behaviour
AUTH_TOKEN_TTL_SECONDS = 60 * 60 AUTH_TOKEN_TTL_SECONDS = 60 * 60
+7
View File
@@ -115,6 +115,13 @@ import_duration_seconds = Histogram(
buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200), buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200),
) )
# Background worker
worker_tasks_total = Counter(
"scrobbler_worker_tasks_total",
"Worker task runs that did work (queue tasks) or ran (periodic tasks), and failures",
["task", "outcome"],
)
# Database # Database
db_query_duration_seconds = Histogram( db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds", "scrobbler_db_query_duration_seconds",
+16 -12
View File
@@ -569,15 +569,19 @@ def _finish(job: ImportJob, status: str, error: str | None = None) -> None:
events.send(events.import_finished, db.session.get(User, job.user_id), job=job) events.send(events.import_finished, db.session.get(User, job.user_id), job=job)
def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None: def work_once() -> bool:
requeue_stalled() """Worker task: process the oldest waiting import, if any."""
while True: job = claim_next_job()
job = claim_next_job() if job is None:
if job is not None: return False
log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id) log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id)
process_job(job) process_job(job)
log.info("import job %s finished: %s", job.id, job.status) log.info("import job %s finished", job.id)
continue return True
if once:
return
time.sleep(poll_seconds) def register_worker_tasks() -> None:
from scrobbler import worker
worker.register_task("imports", work_once)
worker.register_periodic("imports.requeue_stalled", 60, requeue_stalled)
+83
View File
@@ -0,0 +1,83 @@
"""The background worker: runs tasks that modules register (`flask worker`).
Modules register work at app start-up; the worker itself knows nothing about them.
register_task(name, fn) fn() -> bool: True if it did some work.
Called repeatedly while there's work.
register_periodic(name, seconds, fn) fn() every `seconds` (and once at start).
A task that raises is logged, counted and rolled back; the other tasks keep running.
"""
import logging
import time
from collections.abc import Callable
from dataclasses import dataclass
from scrobbler import metrics
from scrobbler.extensions import db
log = logging.getLogger(__name__)
@dataclass
class _Task:
name: str
fn: Callable[[], object]
every: float | None = None # seconds, for periodic tasks
next_run: float = 0.0 # monotonic time; 0 = run at the first opportunity
_tasks: dict[str, _Task] = {}
def register_task(name: str, fn: Callable[[], bool]) -> None:
_tasks[name] = _Task(name, fn)
def register_periodic(name: str, every_seconds: float, fn: Callable[[], object]) -> None:
_tasks[name] = _Task(name, fn, every=every_seconds)
def registered() -> list[str]:
return sorted(_tasks)
def _call(task: _Task) -> bool:
try:
worked = bool(task.fn())
except Exception:
log.exception("worker task %s failed", task.name)
db.session.rollback()
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
return False
if worked or task.every is not None:
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
return worked
def run_once() -> bool:
"""One pass: due periodic tasks, then each queue task once. True if any queue
task did work (so there may be more waiting)."""
now = time.monotonic()
worked = False
for task in list(_tasks.values()):
if task.every is not None:
if now >= task.next_run:
task.next_run = now + task.every
_call(task)
elif _call(task):
worked = True
return worked
def run(poll_seconds: float = 2.0, once: bool = False) -> None:
"""Run until stopped. With once=True, run until there's no more work, then return."""
for task in _tasks.values():
task.next_run = 0.0
while True:
if run_once():
continue
if once:
return
time.sleep(poll_seconds)
+2 -2
View File
@@ -1,7 +1,7 @@
import time import time
from contextlib import contextmanager from contextlib import contextmanager
from scrobbler import events from scrobbler import events, worker
from scrobbler.services import imports, scrobbles from scrobbler.services import imports, scrobbles
from scrobbler.services.scrobbles import TrackInput 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" csv = f"Artist,,One,{when}\nArtist,,One,{when}\nArtist,,Two,{when}\n"
job = imports.create_file_import(user, "export.csv", csv.encode()) job = imports.create_file_import(user, "export.csv", csv.encode())
with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished: with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished:
imports.run_worker(once=True) worker.run(once=True)
[(_, kwargs)] = stored [(_, kwargs)] = stored
assert kwargs["source"] == "import" assert kwargs["source"] == "import"
assert sorted(s.track for s in kwargs["scrobbles"]) == ["One", "Two"] # the repeat once 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 import pytest
from werkzeug.serving import make_server from werkzeug.serving import make_server
from scrobbler import worker
from scrobbler.extensions import db from scrobbler.extensions import db
from scrobbler.models import ImportJob, Scrobble from scrobbler.models import ImportJob, Scrobble
from scrobbler.services import imports from scrobbler.services import imports
@@ -29,7 +30,7 @@ def stored(user):
def run_all(): def run_all():
imports.run_worker(once=True) worker.run(once=True)
db.session.expire_all() db.session.expire_all()
+2 -2
View File
@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta
import pytest import pytest
from scrobbler.services import imports from scrobbler import worker
def csv_bytes(n=3) -> bytes: def csv_bytes(n=3) -> bytes:
@@ -45,7 +45,7 @@ def test_upload_then_follow_progress(client, auth):
job = response.get_json() job = response.get_json()
assert (job["source"], job["status"], job["filename"]) == ("csv", "pending", "export.csv") 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() done = client.get(f"/api/v1/imports/{job['id']}", headers=auth).get_json()
assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3) assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3)
assert client.get("/api/v1/me/summary", headers=auth).get_json()["scrobbles"] == 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