Generic background worker (phase 0, step 2)
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:
1 parent
59ff1bdfa0
commit
098eab025f
13 files changed
+292
-42
No files matched your search
@@ -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
|
||||
|
||||
|
||||
+36
-14
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user