diff --git a/README.md b/README.md index ca193b5..001cfad 100644 --- a/README.md +++ b/README.md @@ -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. - **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`. -- **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. ## 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 | | `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_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 | 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 run --port 5050 # API (port 5000 is taken by AirPlay on macOS) 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 ruff check && uv run ruff format --check ``` diff --git a/deploy/grafana/dashboards/usage.json b/deploy/grafana/dashboards/usage.json index ffd61d4..d230503 100644 --- a/deploy/grafana/dashboards/usage.json +++ b/deploy/grafana/dashboards/usage.json @@ -572,7 +572,7 @@ }, { "type": "row", - "title": "Imports", + "title": "Background work", "id": 13, "collapsed": false, "gridPos": { @@ -878,6 +878,67 @@ "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", "title": "Import duration (p95)", @@ -921,10 +982,10 @@ "sort": "desc" } }, - "id": 19, + "id": 20, "gridPos": { - "x": 12, - "y": 38, + "x": 0, + "y": 46, "w": 12, "h": 8 } diff --git a/docker-compose.yml b/docker-compose.yml index 31dff55..c9cfe75 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -42,13 +42,13 @@ services: db: condition: service_healthy - # Processes history imports (uploaded exports and pulls from Last.fm). + # Background work: history imports, and tasks registered by optional modules. worker: image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local} build: context: . dockerfile: docker/api.Dockerfile - command: ["flask", "--app", "scrobbler", "imports", "worker"] + command: ["flask", "--app", "scrobbler", "worker"] environment: DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler SECRET_KEY: ${SECRET_KEY:-change-me} diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index e90c2a8..59b9f86 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -37,9 +37,12 @@ def create_app(config_object=None): 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) + import_service.register_worker_tasks() from scrobbler.metrics import db as db_metrics diff --git a/src/scrobbler/cli.py b/src/scrobbler/cli.py index d0a93b9..104e021 100644 --- a/src/scrobbler/cli.py +++ b/src/scrobbler/cli.py @@ -2,22 +2,44 @@ import logging import click 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.command("worker") -@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.") -@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.") -@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.") -def worker(once: bool, poll: float, metrics: bool) -> None: - """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) +@_worker_options +def imports_worker(once: bool, poll: float, serve_metrics: bool) -> None: + """Alias for `flask worker` (kept for existing deployments).""" + _run_worker(once, poll, serve_metrics) diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index a6c3f2c..b29ad68 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -56,7 +56,10 @@ class Config: 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))) 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 AUTH_TOKEN_TTL_SECONDS = 60 * 60 diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index b121678..61c8f1b 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -115,6 +115,13 @@ import_duration_seconds = Histogram( 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 db_query_duration_seconds = Histogram( "scrobbler_db_query_duration_seconds", diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index e8d8139..58a6978 100644 --- a/src/scrobbler/services/imports.py +++ b/src/scrobbler/services/imports.py @@ -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) -def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None: - requeue_stalled() - while True: - job = claim_next_job() - if job is not None: - log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id) - process_job(job) - log.info("import job %s finished: %s", job.id, job.status) - continue - if once: - return - time.sleep(poll_seconds) +def work_once() -> bool: + """Worker task: process the oldest waiting import, if any.""" + job = claim_next_job() + if job is None: + return False + log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id) + process_job(job) + log.info("import job %s finished", job.id) + return True + + +def register_worker_tasks() -> None: + from scrobbler import worker + + worker.register_task("imports", work_once) + worker.register_periodic("imports.requeue_stalled", 60, requeue_stalled) diff --git a/src/scrobbler/worker.py b/src/scrobbler/worker.py new file mode 100644 index 0000000..c69decb --- /dev/null +++ b/src/scrobbler/worker.py @@ -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) diff --git a/tests/test_events.py b/tests/test_events.py index ed99ded..c75be6d 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -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 diff --git a/tests/test_imports.py b/tests/test_imports.py index 708f853..b53cc33 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -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() diff --git a/tests/test_ui_imports.py b/tests/test_ui_imports.py index add0dcb..f7d55ea 100644 --- a/tests/test_ui_imports.py +++ b/tests/test_ui_imports.py @@ -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 diff --git a/tests/test_worker.py b/tests/test_worker.py new file mode 100644 index 0000000..36ae8a4 --- /dev/null +++ b/tests/test_worker.py @@ -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