Worker tasks are registered per app
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 1m46s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 1m46s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
The task registry was module-global, so tasks registered by an app with federation enabled would also run under an app without it (and break the "federation off registers nothing" guarantee depending on order). Tasks now live on each app (app.extensions["worker_tasks"]); register_task/register_periodic take the app, and the worker runs the current app's tasks. 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
d49aa72be1
commit
c1a7dd0877
5 files changed
+55
-24
No files matched your search
@@ -46,7 +46,7 @@ def create_app(config_object=None):
|
|||||||
|
|
||||||
app.cli.add_command(worker_command)
|
app.cli.add_command(worker_command)
|
||||||
app.cli.add_command(imports_cli)
|
app.cli.add_command(imports_cli)
|
||||||
import_service.register_worker_tasks()
|
import_service.register_worker_tasks(app)
|
||||||
|
|
||||||
from scrobbler.metrics import db as db_metrics
|
from scrobbler.metrics import db as db_metrics
|
||||||
|
|
||||||
|
|||||||
@@ -580,8 +580,8 @@ def work_once() -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def register_worker_tasks() -> None:
|
def register_worker_tasks(app) -> None:
|
||||||
from scrobbler import worker
|
from scrobbler import worker
|
||||||
|
|
||||||
worker.register_task("imports", work_once)
|
worker.register_task(app, "imports", work_once)
|
||||||
worker.register_periodic("imports.requeue_stalled", 60, requeue_stalled)
|
worker.register_periodic(app, "imports.requeue_stalled", 60, requeue_stalled)
|
||||||
+18
-12
@@ -1,10 +1,11 @@
|
|||||||
"""The background worker: runs tasks that modules register (`flask worker`).
|
"""The background worker: runs tasks that modules register (`flask worker`).
|
||||||
|
|
||||||
Modules register work at app start-up; the worker itself knows nothing about them.
|
Modules register work on an app at start-up; the worker itself knows nothing about them.
|
||||||
|
Each app has its own tasks, so apps with different modules enabled never share them.
|
||||||
|
|
||||||
register_task(name, fn) fn() -> bool: True if it did some work.
|
register_task(app, name, fn) fn() -> bool: True if it did some work.
|
||||||
Called repeatedly while there's work.
|
Called repeatedly while there's work.
|
||||||
register_periodic(name, seconds, fn) fn() every `seconds` (and once at start).
|
register_periodic(app, 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.
|
A task that raises is logged, counted and rolled back; the other tasks keep running.
|
||||||
"""
|
"""
|
||||||
@@ -14,6 +15,8 @@ import time
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from flask import Flask, current_app
|
||||||
|
|
||||||
from scrobbler import metrics
|
from scrobbler import metrics
|
||||||
from scrobbler.extensions import db
|
from scrobbler.extensions import db
|
||||||
|
|
||||||
@@ -28,19 +31,22 @@ class _Task:
|
|||||||
next_run: float = 0.0 # monotonic time; 0 = run at the first opportunity
|
next_run: float = 0.0 # monotonic time; 0 = run at the first opportunity
|
||||||
|
|
||||||
|
|
||||||
_tasks: dict[str, _Task] = {}
|
def tasks(app: Flask | None = None) -> dict[str, _Task]:
|
||||||
|
return (app or current_app).extensions.setdefault("worker_tasks", {})
|
||||||
|
|
||||||
|
|
||||||
def register_task(name: str, fn: Callable[[], bool]) -> None:
|
def register_task(app: Flask, name: str, fn: Callable[[], bool]) -> None:
|
||||||
_tasks[name] = _Task(name, fn)
|
tasks(app)[name] = _Task(name, fn)
|
||||||
|
|
||||||
|
|
||||||
def register_periodic(name: str, every_seconds: float, fn: Callable[[], object]) -> None:
|
def register_periodic(
|
||||||
_tasks[name] = _Task(name, fn, every=every_seconds)
|
app: Flask, name: str, every_seconds: float, fn: Callable[[], object]
|
||||||
|
) -> None:
|
||||||
|
tasks(app)[name] = _Task(name, fn, every=every_seconds)
|
||||||
|
|
||||||
|
|
||||||
def registered() -> list[str]:
|
def registered(app: Flask | None = None) -> list[str]:
|
||||||
return sorted(_tasks)
|
return sorted(tasks(app))
|
||||||
|
|
||||||
|
|
||||||
def _call(task: _Task) -> bool:
|
def _call(task: _Task) -> bool:
|
||||||
@@ -61,7 +67,7 @@ def run_once() -> bool:
|
|||||||
task did work (so there may be more waiting)."""
|
task did work (so there may be more waiting)."""
|
||||||
now = time.monotonic()
|
now = time.monotonic()
|
||||||
worked = False
|
worked = False
|
||||||
for task in list(_tasks.values()):
|
for task in list(tasks().values()):
|
||||||
if task.every is not None:
|
if task.every is not None:
|
||||||
if now >= task.next_run:
|
if now >= task.next_run:
|
||||||
task.next_run = now + task.every
|
task.next_run = now + task.every
|
||||||
@@ -73,7 +79,7 @@ def run_once() -> bool:
|
|||||||
|
|
||||||
def run(poll_seconds: float = 2.0, once: bool = False) -> None:
|
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."""
|
"""Run until stopped. With once=True, run until there's no more work, then return."""
|
||||||
for task in _tasks.values():
|
for task in tasks().values():
|
||||||
task.next_run = 0.0
|
task.next_run = 0.0
|
||||||
while True:
|
while True:
|
||||||
if run_once():
|
if run_once():
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ def test_nothing_is_registered_when_federation_is_off(app):
|
|||||||
assert views == []
|
assert views == []
|
||||||
for signal in (events.scrobbles_stored, events.now_playing_changed, events.import_finished):
|
for signal in (events.scrobbles_stored, events.now_playing_changed, events.import_finished):
|
||||||
assert not any(_from_federation(r) for r in signal.receivers_for(None))
|
assert not any(_from_federation(r) for r in signal.receivers_for(None))
|
||||||
assert not any(name.startswith("federation") for name in worker.registered())
|
assert not any(name.startswith("federation") for name in worker.registered(app))
|
||||||
|
|
||||||
|
|
||||||
class _Enabled(TestConfig):
|
class _Enabled(TestConfig):
|
||||||
|
|||||||
+32
-7
@@ -3,18 +3,43 @@ import pytest
|
|||||||
from scrobbler import worker
|
from scrobbler import worker
|
||||||
|
|
||||||
|
|
||||||
|
class _Registry:
|
||||||
|
"""The worker module, bound to the test app, with an emptied task registry."""
|
||||||
|
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
def register_task(self, name, fn):
|
||||||
|
worker.register_task(self.app, name, fn)
|
||||||
|
|
||||||
|
def register_periodic(self, name, every, fn):
|
||||||
|
worker.register_periodic(self.app, name, every, fn)
|
||||||
|
|
||||||
|
def run(self, **kwargs):
|
||||||
|
worker.run(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def tasks(app):
|
def tasks(app):
|
||||||
"""An empty task registry for the test, restored afterwards."""
|
"""An empty task registry for the test app, restored afterwards."""
|
||||||
saved = dict(worker._tasks)
|
registry = worker.tasks(app)
|
||||||
worker._tasks.clear()
|
saved = dict(registry)
|
||||||
yield worker
|
registry.clear()
|
||||||
worker._tasks.clear()
|
yield _Registry(app)
|
||||||
worker._tasks.update(saved)
|
registry.clear()
|
||||||
|
registry.update(saved)
|
||||||
|
|
||||||
|
|
||||||
def test_imports_are_registered_by_the_app(app):
|
def test_imports_are_registered_by_the_app(app):
|
||||||
assert {"imports", "imports.requeue_stalled"} <= set(worker.registered())
|
assert {"imports", "imports.requeue_stalled"} <= set(worker.registered(app))
|
||||||
|
|
||||||
|
|
||||||
|
def test_apps_have_their_own_tasks(app, fed_app):
|
||||||
|
worker.register_task(fed_app, "only-on-fed-app", lambda: False)
|
||||||
|
try:
|
||||||
|
assert "only-on-fed-app" not in worker.registered(app)
|
||||||
|
finally:
|
||||||
|
worker.tasks(fed_app).pop("only-on-fed-app")
|
||||||
|
|
||||||
|
|
||||||
def test_queue_tasks_run_until_there_is_no_work(tasks, metric_delta):
|
def test_queue_tasks_run_until_there_is_no_work(tasks, metric_delta):
|
||||||
|
|||||||
Reference in new issue
Block a user