simple-module-background-tasks 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- simple_module_background_tasks-0.0.1/.gitignore +59 -0
- simple_module_background_tasks-0.0.1/LICENSE +21 -0
- simple_module_background_tasks-0.0.1/PKG-INFO +92 -0
- simple_module_background_tasks-0.0.1/README.md +62 -0
- simple_module_background_tasks-0.0.1/background_tasks/__init__.py +1 -0
- simple_module_background_tasks-0.0.1/background_tasks/_signal_support.py +105 -0
- simple_module_background_tasks-0.0.1/background_tasks/celery_app.py +95 -0
- simple_module_background_tasks-0.0.1/background_tasks/constants.py +75 -0
- simple_module_background_tasks-0.0.1/background_tasks/contracts/__init__.py +1 -0
- simple_module_background_tasks-0.0.1/background_tasks/contracts/events.py +26 -0
- simple_module_background_tasks-0.0.1/background_tasks/contracts/schemas.py +66 -0
- simple_module_background_tasks-0.0.1/background_tasks/deps.py +19 -0
- simple_module_background_tasks-0.0.1/background_tasks/endpoints/__init__.py +0 -0
- simple_module_background_tasks-0.0.1/background_tasks/endpoints/api_admin.py +62 -0
- simple_module_background_tasks-0.0.1/background_tasks/endpoints/views.py +71 -0
- simple_module_background_tasks-0.0.1/background_tasks/locales/en.json +57 -0
- simple_module_background_tasks-0.0.1/background_tasks/models.py +86 -0
- simple_module_background_tasks-0.0.1/background_tasks/module.py +121 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/Detail.tsx +180 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/Index.tsx +181 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/components/ExecutionRow.tsx +79 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/components/RetryConfirmDialog.tsx +38 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/constants.ts +49 -0
- simple_module_background_tasks-0.0.1/background_tasks/pages/retry.ts +42 -0
- simple_module_background_tasks-0.0.1/background_tasks/py.typed +0 -0
- simple_module_background_tasks-0.0.1/background_tasks/service.py +138 -0
- simple_module_background_tasks-0.0.1/background_tasks/services.py +25 -0
- simple_module_background_tasks-0.0.1/background_tasks/settings.py +83 -0
- simple_module_background_tasks-0.0.1/background_tasks/signals.py +286 -0
- simple_module_background_tasks-0.0.1/background_tasks/sync_db.py +82 -0
- simple_module_background_tasks-0.0.1/background_tasks/tasks.py +105 -0
- simple_module_background_tasks-0.0.1/package.json +16 -0
- simple_module_background_tasks-0.0.1/pyproject.toml +55 -0
- simple_module_background_tasks-0.0.1/tests/test_admin_api.py +107 -0
- simple_module_background_tasks-0.0.1/tests/test_bg_service.py +187 -0
- simple_module_background_tasks-0.0.1/tests/test_signals.py +286 -0
- simple_module_background_tasks-0.0.1/tsconfig.json +11 -0
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
dist/
|
|
6
|
+
build/
|
|
7
|
+
.venv/
|
|
8
|
+
*.egg
|
|
9
|
+
|
|
10
|
+
# UV
|
|
11
|
+
uv.lock
|
|
12
|
+
|
|
13
|
+
# Node
|
|
14
|
+
node_modules/
|
|
15
|
+
|
|
16
|
+
# IDE
|
|
17
|
+
.idea/
|
|
18
|
+
.vscode/
|
|
19
|
+
*.swp
|
|
20
|
+
*.swo
|
|
21
|
+
|
|
22
|
+
# Environment
|
|
23
|
+
.env
|
|
24
|
+
|
|
25
|
+
# Database
|
|
26
|
+
*.db
|
|
27
|
+
*.sqlite3
|
|
28
|
+
|
|
29
|
+
# Module-managed runtime state (e.g. uploaded dataset files,
|
|
30
|
+
# default storage_dir for SM_DATASETS_STORAGE_DIR).
|
|
31
|
+
var/
|
|
32
|
+
|
|
33
|
+
# file_storage filesystem backend default root (override via SM_FILE_STORAGE_FS_ROOT_PATH).
|
|
34
|
+
uploads/
|
|
35
|
+
|
|
36
|
+
# Vite
|
|
37
|
+
host/static/dist/
|
|
38
|
+
|
|
39
|
+
# Auto-generated frontend module manifest (regenerated by the host at boot
|
|
40
|
+
# or via `make gen-pages`).
|
|
41
|
+
host/client_app/modules.manifest.json
|
|
42
|
+
host/client_app/modules.generated.ts
|
|
43
|
+
host/client_app/modules.generated.css
|
|
44
|
+
|
|
45
|
+
# Worktrees
|
|
46
|
+
.worktrees/
|
|
47
|
+
|
|
48
|
+
# Performance profiles
|
|
49
|
+
.memray/
|
|
50
|
+
.benchmarks/
|
|
51
|
+
|
|
52
|
+
# OS
|
|
53
|
+
.DS_Store
|
|
54
|
+
Thumbs.db
|
|
55
|
+
|
|
56
|
+
.playwright-cli/*
|
|
57
|
+
.playwright-mcp/*
|
|
58
|
+
host/client_app/.playwright-cli/*
|
|
59
|
+
.superpowers/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Anto Subash
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simple_module_background_tasks
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Celery + Redis task queue with admin UI for monitoring and retrying failed/stuck tasks
|
|
5
|
+
Project-URL: Homepage, https://github.com/antosubash/simple_module_python
|
|
6
|
+
Project-URL: Repository, https://github.com/antosubash/simple_module_python
|
|
7
|
+
Project-URL: Issues, https://github.com/antosubash/simple_module_python/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/antosubash/simple_module_python/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Anto Subash <antosubash@live.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: background-jobs,celery,redis,simple-module,task-queue
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Framework :: FastAPI
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.12
|
|
24
|
+
Requires-Dist: celery[redis]>=5.4
|
|
25
|
+
Requires-Dist: redis>=5
|
|
26
|
+
Requires-Dist: simple-module-core==0.0.1
|
|
27
|
+
Requires-Dist: simple-module-db==0.0.1
|
|
28
|
+
Requires-Dist: simple-module-hosting==0.0.1
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# simple_module_background_tasks
|
|
32
|
+
|
|
33
|
+
Celery + Redis background-task module for [simple_module](https://github.com/antosubash/simple_module_python) apps. Provides a pre-configured Celery instance, a task registration hook, and an admin UI for monitoring + retrying failed/stuck tasks.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install simple_module_background_tasks
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Requires a Redis broker — set `SM_CELERY_BROKER_URL` (default `redis://localhost:6379/0`).
|
|
42
|
+
|
|
43
|
+
## What it provides
|
|
44
|
+
|
|
45
|
+
- `register_background_tasks()` module hook — modules declare tasks here; the registry wires them into the Celery app at boot.
|
|
46
|
+
- Admin UI at `/background-tasks/admin` — list recent runs, retry failed, inspect tracebacks.
|
|
47
|
+
- Shared Celery app accessible via `from background_tasks import celery_app` (import name `background_tasks`, distribution name `simple_module_background_tasks`).
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
Declare a task in a module:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
# modules/reports/reports/tasks.py
|
|
55
|
+
from background_tasks import celery_app # type: ignore[import-not-found]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@celery_app.task(name="reports.generate")
|
|
59
|
+
def generate_report(report_id: int) -> None:
|
|
60
|
+
...
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Register it:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
class ReportsModule(ModuleBase):
|
|
67
|
+
meta = ModuleMeta(name="reports", depends_on=["background_tasks"])
|
|
68
|
+
|
|
69
|
+
def register_background_tasks(self):
|
|
70
|
+
from . import tasks # noqa: F401 — side-effect: registers tasks
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Enqueue from an endpoint:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
generate_report.delay(report_id=42)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Run a worker locally:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
uv run celery -A background_tasks.celery_app worker --loglevel=info
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Depends on
|
|
86
|
+
|
|
87
|
+
- `simple_module_core`, `simple_module_db`, `simple_module_hosting`
|
|
88
|
+
- `celery[redis]>=5.4`, `redis>=5`
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
MIT — see [LICENSE](https://github.com/antosubash/simple_module_python/blob/main/LICENSE).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# simple_module_background_tasks
|
|
2
|
+
|
|
3
|
+
Celery + Redis background-task module for [simple_module](https://github.com/antosubash/simple_module_python) apps. Provides a pre-configured Celery instance, a task registration hook, and an admin UI for monitoring + retrying failed/stuck tasks.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install simple_module_background_tasks
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires a Redis broker — set `SM_CELERY_BROKER_URL` (default `redis://localhost:6379/0`).
|
|
12
|
+
|
|
13
|
+
## What it provides
|
|
14
|
+
|
|
15
|
+
- `register_background_tasks()` module hook — modules declare tasks here; the registry wires them into the Celery app at boot.
|
|
16
|
+
- Admin UI at `/background-tasks/admin` — list recent runs, retry failed, inspect tracebacks.
|
|
17
|
+
- Shared Celery app accessible via `from background_tasks import celery_app` (import name `background_tasks`, distribution name `simple_module_background_tasks`).
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
Declare a task in a module:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
# modules/reports/reports/tasks.py
|
|
25
|
+
from background_tasks import celery_app # type: ignore[import-not-found]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@celery_app.task(name="reports.generate")
|
|
29
|
+
def generate_report(report_id: int) -> None:
|
|
30
|
+
...
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Register it:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
class ReportsModule(ModuleBase):
|
|
37
|
+
meta = ModuleMeta(name="reports", depends_on=["background_tasks"])
|
|
38
|
+
|
|
39
|
+
def register_background_tasks(self):
|
|
40
|
+
from . import tasks # noqa: F401 — side-effect: registers tasks
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Enqueue from an endpoint:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
generate_report.delay(report_id=42)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Run a worker locally:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv run celery -A background_tasks.celery_app worker --loglevel=info
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Depends on
|
|
56
|
+
|
|
57
|
+
- `simple_module_core`, `simple_module_db`, `simple_module_hosting`
|
|
58
|
+
- `celery[redis]>=5.4`, `redis>=5`
|
|
59
|
+
|
|
60
|
+
## License
|
|
61
|
+
|
|
62
|
+
MIT — see [LICENSE](https://github.com/antosubash/simple_module_python/blob/main/LICENSE).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""BackgroundTasks module — Celery + Redis task queue with admin UI."""
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Signal-handler helpers shared across :mod:`background_tasks.signals`.
|
|
2
|
+
|
|
3
|
+
Kept in a separate module so :mod:`.signals` stays under the 300-line cap.
|
|
4
|
+
These helpers are intentionally side-effect-free except for the DB write in
|
|
5
|
+
``upsert_by_celery_id`` — signal handlers compose them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import traceback as tb_mod
|
|
11
|
+
from datetime import UTC, datetime
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from sqlalchemy import select
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
|
|
17
|
+
from background_tasks.models import TaskExecution
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def now_utc() -> datetime:
|
|
21
|
+
return datetime.now(UTC)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def coerce_args_kwargs(args: Any, kwargs: Any) -> tuple[list[Any], dict[str, Any]]:
|
|
25
|
+
"""Normalise Celery args/kwargs payloads to JSON-ready shapes.
|
|
26
|
+
|
|
27
|
+
Celery sometimes hands us tuples/frozensets that our JSON column can't
|
|
28
|
+
store; also tolerates ``None`` so a partial payload won't wedge the row.
|
|
29
|
+
"""
|
|
30
|
+
safe_args: list[Any] = list(args) if args else []
|
|
31
|
+
safe_kwargs: dict[str, Any] = dict(kwargs) if kwargs else {}
|
|
32
|
+
return safe_args, safe_kwargs
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def upsert_by_celery_id(
|
|
36
|
+
session: Session,
|
|
37
|
+
*,
|
|
38
|
+
celery_task_id: str | None,
|
|
39
|
+
defaults: dict[str, Any],
|
|
40
|
+
) -> TaskExecution:
|
|
41
|
+
"""Fetch the row for ``celery_task_id``, or create it from ``defaults``.
|
|
42
|
+
|
|
43
|
+
``defaults`` must include ``task_name`` (it's NOT NULL on the table).
|
|
44
|
+
Handlers never race on the same row within a worker process — Celery
|
|
45
|
+
serialises per-task signals — so this is upsert-by-read, no advisory
|
|
46
|
+
locks needed.
|
|
47
|
+
"""
|
|
48
|
+
row: TaskExecution | None = None
|
|
49
|
+
if celery_task_id:
|
|
50
|
+
stmt = select(TaskExecution).where(TaskExecution.celery_task_id == celery_task_id)
|
|
51
|
+
row = session.execute(stmt).scalar_one_or_none()
|
|
52
|
+
if row is None:
|
|
53
|
+
row = TaskExecution(celery_task_id=celery_task_id, **defaults)
|
|
54
|
+
session.add(row)
|
|
55
|
+
else:
|
|
56
|
+
for key, value in defaults.items():
|
|
57
|
+
setattr(row, key, value)
|
|
58
|
+
return row
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def task_name_of(sender: Any, task: Any = None) -> str:
|
|
62
|
+
"""Best-effort resolution of a task's registered name from signal args."""
|
|
63
|
+
return (
|
|
64
|
+
(isinstance(sender, str) and sender)
|
|
65
|
+
or getattr(task, "name", None)
|
|
66
|
+
or getattr(sender, "name", None)
|
|
67
|
+
or "unknown"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def task_id_from(sender: Any = None, request: Any = None) -> str | None:
|
|
72
|
+
"""Pull the Celery task UUID out of whichever signal-arg carries it.
|
|
73
|
+
|
|
74
|
+
Celery's signals pass the task id via three different shapes depending
|
|
75
|
+
on the signal: ``task_id=`` kwarg, ``request.id``, or ``sender.request.id``.
|
|
76
|
+
Centralising the probe keeps the per-handler code boring.
|
|
77
|
+
"""
|
|
78
|
+
if request is not None:
|
|
79
|
+
tid = getattr(request, "id", None)
|
|
80
|
+
if tid:
|
|
81
|
+
return tid
|
|
82
|
+
sender_request = getattr(sender, "request", None)
|
|
83
|
+
return getattr(sender_request, "id", None) if sender_request is not None else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def jsonable_result(result: Any) -> dict[str, Any] | None:
|
|
87
|
+
"""Wrap arbitrary task results in a JSON-storable shape."""
|
|
88
|
+
if result is None:
|
|
89
|
+
return None
|
|
90
|
+
if isinstance(result, dict):
|
|
91
|
+
return result
|
|
92
|
+
try:
|
|
93
|
+
return {"value": result}
|
|
94
|
+
except Exception:
|
|
95
|
+
return {"value": repr(result)}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def render_traceback(einfo: Any, exception: BaseException | None) -> str | None:
|
|
99
|
+
"""Prefer Celery's pre-formatted traceback; fall back to the live exception."""
|
|
100
|
+
tb = getattr(einfo, "traceback", None)
|
|
101
|
+
if tb:
|
|
102
|
+
return str(tb)
|
|
103
|
+
if exception is not None:
|
|
104
|
+
return "".join(tb_mod.format_exception(type(exception), exception, exception.__traceback__))
|
|
105
|
+
return None
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Build and configure the Celery application.
|
|
2
|
+
|
|
3
|
+
Invoked from two places:
|
|
4
|
+
|
|
5
|
+
- :meth:`BackgroundTasksModule.on_startup` in the web process, so the API
|
|
6
|
+
can enqueue tasks via ``app.state.background_tasks.celery.send_task(...)``.
|
|
7
|
+
- ``scripts/run_worker.py`` at worker boot, so the worker process uses an
|
|
8
|
+
identical config (broker URL, signal handlers, autodiscovered tasks).
|
|
9
|
+
|
|
10
|
+
Task discovery uses :py:meth:`celery.Celery.autodiscover_tasks` with the
|
|
11
|
+
top-level package name of every installed module (enumerated via the
|
|
12
|
+
``simple_module`` entry-point group). Any module that ships a ``tasks.py``
|
|
13
|
+
is picked up automatically — no framework hook, no per-module registration.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import logging
|
|
19
|
+
from importlib.metadata import entry_points
|
|
20
|
+
|
|
21
|
+
from celery import Celery
|
|
22
|
+
from celery.schedules import schedule
|
|
23
|
+
from simple_module_core.discovery import ENTRY_POINT_GROUP
|
|
24
|
+
|
|
25
|
+
from background_tasks.constants import (
|
|
26
|
+
INTERNAL_TASK_PURGE_OLD,
|
|
27
|
+
INTERNAL_TASK_SWEEP_STUCK,
|
|
28
|
+
MODULE_NAME,
|
|
29
|
+
)
|
|
30
|
+
from background_tasks.settings import BackgroundTasksSettings
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _discover_task_packages() -> list[str]:
|
|
36
|
+
"""Return the top-level package name of every installed simple_module.
|
|
37
|
+
|
|
38
|
+
Celery's ``autodiscover_tasks`` imports ``<package>.tasks`` for each name
|
|
39
|
+
returned here, so any module that ships a ``tasks.py`` registers its
|
|
40
|
+
tasks without a per-module hook.
|
|
41
|
+
"""
|
|
42
|
+
packages: set[str] = set()
|
|
43
|
+
for ep in entry_points(group=ENTRY_POINT_GROUP):
|
|
44
|
+
module_path = ep.value.split(":", 1)[0]
|
|
45
|
+
top_level = module_path.split(".", 1)[0]
|
|
46
|
+
packages.add(top_level)
|
|
47
|
+
return sorted(packages)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_celery(settings: BackgroundTasksSettings) -> Celery:
|
|
51
|
+
"""Construct a Celery app wired to the project's Redis broker."""
|
|
52
|
+
celery = Celery(MODULE_NAME)
|
|
53
|
+
|
|
54
|
+
celery.conf.update(
|
|
55
|
+
broker_url=settings.broker_url,
|
|
56
|
+
result_backend=settings.result_backend,
|
|
57
|
+
task_default_queue=settings.task_default_queue,
|
|
58
|
+
# ``task_track_started`` gives us the ``STARTED`` state so
|
|
59
|
+
# ``task_prerun`` can flip our row to ``running``.
|
|
60
|
+
task_track_started=True,
|
|
61
|
+
# ``task_acks_late`` + ``worker_prefetch_multiplier=1`` gives us
|
|
62
|
+
# at-least-once semantics, which matches how the admin UI asks users
|
|
63
|
+
# to think about retries — duplicates beat lost work.
|
|
64
|
+
task_acks_late=True,
|
|
65
|
+
worker_prefetch_multiplier=1,
|
|
66
|
+
task_serializer="json",
|
|
67
|
+
result_serializer="json",
|
|
68
|
+
accept_content=["json"],
|
|
69
|
+
timezone="UTC",
|
|
70
|
+
enable_utc=True,
|
|
71
|
+
broker_connection_retry_on_startup=True,
|
|
72
|
+
beat_schedule={
|
|
73
|
+
"background-tasks-sweep-stuck": {
|
|
74
|
+
"task": INTERNAL_TASK_SWEEP_STUCK,
|
|
75
|
+
"schedule": schedule(settings.stuck_sweep_interval_seconds),
|
|
76
|
+
},
|
|
77
|
+
"background-tasks-purge-old": {
|
|
78
|
+
"task": INTERNAL_TASK_PURGE_OLD,
|
|
79
|
+
"schedule": schedule(settings.purge_interval_seconds),
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
beat_scheduler="celery.beat:PersistentScheduler",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Autodiscover across every installed simple_module — a module just ships
|
|
86
|
+
# a `tasks.py` and the worker picks it up.
|
|
87
|
+
packages = _discover_task_packages()
|
|
88
|
+
logger.info("Celery autodiscover_tasks across: %s", packages)
|
|
89
|
+
celery.autodiscover_tasks(packages, related_name="tasks", force=True)
|
|
90
|
+
|
|
91
|
+
# Side-effect import: connects signal handlers to this Celery instance's
|
|
92
|
+
# ``celery.signals.*`` globals. Safe to import repeatedly.
|
|
93
|
+
from background_tasks import signals # noqa: F401
|
|
94
|
+
|
|
95
|
+
return celery
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Single source of truth for background_tasks module string literals.
|
|
2
|
+
|
|
3
|
+
Anything that would otherwise become a magic string — table names, env-var
|
|
4
|
+
prefixes, permission codes, route segments, page identifiers, task-status
|
|
5
|
+
values — lives here so models, signals, services, endpoints, tests, and
|
|
6
|
+
the frontend all agree on one spelling.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
# ── Module identity ─────────────────────────────────────────────
|
|
14
|
+
MODULE_NAME = "background_tasks"
|
|
15
|
+
MODULE_DISPLAY_NAME = "BackgroundTasks"
|
|
16
|
+
TABLE_PREFIX = "background_tasks_"
|
|
17
|
+
TABLE_TASK_EXECUTION = f"{TABLE_PREFIX}task_execution"
|
|
18
|
+
|
|
19
|
+
# ── Env / settings ──────────────────────────────────────────────
|
|
20
|
+
ENV_PREFIX = "SM_BG_TASKS_"
|
|
21
|
+
|
|
22
|
+
# ── Permissions ─────────────────────────────────────────────────
|
|
23
|
+
PERM_GROUP = "Background Tasks"
|
|
24
|
+
PERM_VIEW = "background_tasks.view"
|
|
25
|
+
PERM_MANAGE = "background_tasks.manage"
|
|
26
|
+
|
|
27
|
+
# ── Routes ──────────────────────────────────────────────────────
|
|
28
|
+
API_PREFIX = "/api/background_tasks"
|
|
29
|
+
VIEW_PREFIX = "/admin/background-tasks"
|
|
30
|
+
ADMIN_ROUTER_PREFIX = "/admin"
|
|
31
|
+
|
|
32
|
+
# ── Menu ────────────────────────────────────────────────────────
|
|
33
|
+
MENU_LABEL = "Background Tasks"
|
|
34
|
+
MENU_ICON = "activity"
|
|
35
|
+
MENU_ORDER = 80
|
|
36
|
+
|
|
37
|
+
# ── Page identifiers ────────────────────────────────────────────
|
|
38
|
+
# Kept as literals at the call site (see endpoints/views.py) so
|
|
39
|
+
# ``make doctor``'s SM003/SM004 static analysis can match pages to renders.
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ── Task statuses ───────────────────────────────────────────────
|
|
43
|
+
class TaskStatus(StrEnum):
|
|
44
|
+
"""Lifecycle state of a single task execution row."""
|
|
45
|
+
|
|
46
|
+
PENDING = "pending"
|
|
47
|
+
RUNNING = "running"
|
|
48
|
+
SUCCESS = "success"
|
|
49
|
+
FAILED = "failed"
|
|
50
|
+
STUCK = "stuck"
|
|
51
|
+
REVOKED = "revoked"
|
|
52
|
+
RETRYING = "retrying"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
RETRYABLE_STATUSES: frozenset[TaskStatus] = frozenset({TaskStatus.FAILED, TaskStatus.STUCK})
|
|
56
|
+
TERMINAL_STATUSES: frozenset[TaskStatus] = frozenset(
|
|
57
|
+
{TaskStatus.SUCCESS, TaskStatus.FAILED, TaskStatus.STUCK, TaskStatus.REVOKED}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# ── Defaults ────────────────────────────────────────────────────
|
|
61
|
+
DEFAULT_QUEUE = "default"
|
|
62
|
+
DEFAULT_BROKER_URL = "redis://localhost:6379/0"
|
|
63
|
+
DEFAULT_RESULT_BACKEND = "redis://localhost:6379/1"
|
|
64
|
+
DEFAULT_STUCK_AFTER_SECONDS = 300
|
|
65
|
+
DEFAULT_STUCK_SWEEP_INTERVAL_SECONDS = 60
|
|
66
|
+
DEFAULT_PURGE_INTERVAL_SECONDS = 60 * 60 * 24
|
|
67
|
+
DEFAULT_RETENTION_DAYS = 14
|
|
68
|
+
DEFAULT_MAX_RETRIES = 3
|
|
69
|
+
|
|
70
|
+
# ── Internal task names ─────────────────────────────────────────
|
|
71
|
+
INTERNAL_TASK_SWEEP_STUCK = "background_tasks.sweep_stuck_tasks"
|
|
72
|
+
INTERNAL_TASK_PURGE_OLD = "background_tasks.purge_old_executions"
|
|
73
|
+
# Harmless round-trip task; only wired into CI smoke tests and local dev —
|
|
74
|
+
# not scheduled, not invoked by other modules.
|
|
75
|
+
DEMO_ECHO_TASK = "background_tasks.demo_echo"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Public contracts for the BackgroundTasks module."""
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Public events emitted by the BackgroundTasks module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from simple_module_core.events import Event
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class TaskFailed(Event):
|
|
13
|
+
"""A task transitioned to ``failed`` — subscribers may alert/log."""
|
|
14
|
+
|
|
15
|
+
task_execution_id: uuid.UUID
|
|
16
|
+
task_name: str
|
|
17
|
+
exception_type: str | None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class TaskRetried(Event):
|
|
22
|
+
"""A failed/stuck task was manually retried via the admin UI."""
|
|
23
|
+
|
|
24
|
+
original_id: uuid.UUID
|
|
25
|
+
new_id: uuid.UUID
|
|
26
|
+
task_name: str
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""DTOs returned by the BackgroundTasks admin API / views."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import ConfigDict
|
|
10
|
+
from sqlmodel import SQLModel
|
|
11
|
+
|
|
12
|
+
from background_tasks.constants import TaskStatus
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TaskExecutionListItem(SQLModel):
|
|
16
|
+
"""Compact row for the admin listing table."""
|
|
17
|
+
|
|
18
|
+
model_config = ConfigDict(from_attributes=True)
|
|
19
|
+
|
|
20
|
+
id: uuid.UUID
|
|
21
|
+
celery_task_id: str | None = None
|
|
22
|
+
task_name: str
|
|
23
|
+
status: TaskStatus
|
|
24
|
+
queue: str
|
|
25
|
+
retries: int
|
|
26
|
+
worker: str | None = None
|
|
27
|
+
queued_at: datetime | None = None
|
|
28
|
+
started_at: datetime | None = None
|
|
29
|
+
finished_at: datetime | None = None
|
|
30
|
+
exception_type: str | None = None
|
|
31
|
+
retried_from_id: uuid.UUID | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class TaskExecutionDetail(SQLModel):
|
|
35
|
+
"""Full row for the detail page (adds args/kwargs/result/traceback)."""
|
|
36
|
+
|
|
37
|
+
model_config = ConfigDict(from_attributes=True)
|
|
38
|
+
|
|
39
|
+
id: uuid.UUID
|
|
40
|
+
celery_task_id: str | None = None
|
|
41
|
+
task_name: str
|
|
42
|
+
status: TaskStatus
|
|
43
|
+
queue: str
|
|
44
|
+
args: list[Any] = []
|
|
45
|
+
kwargs: dict[str, Any] = {}
|
|
46
|
+
result: dict[str, Any] | None = None
|
|
47
|
+
traceback: str | None = None
|
|
48
|
+
exception_type: str | None = None
|
|
49
|
+
worker: str | None = None
|
|
50
|
+
retries: int = 0
|
|
51
|
+
retried_from_id: uuid.UUID | None = None
|
|
52
|
+
queued_at: datetime | None = None
|
|
53
|
+
started_at: datetime | None = None
|
|
54
|
+
finished_at: datetime | None = None
|
|
55
|
+
heartbeat_at: datetime | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class TaskExecutionListResponse(SQLModel):
|
|
59
|
+
"""Paginated response shape used by both the API and Inertia views."""
|
|
60
|
+
|
|
61
|
+
items: list[TaskExecutionListItem]
|
|
62
|
+
total: int
|
|
63
|
+
page: int
|
|
64
|
+
per_page: int
|
|
65
|
+
status: TaskStatus | None = None
|
|
66
|
+
task_name: str | None = None
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""FastAPI dependencies for the BackgroundTasks module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from fastapi import Depends, Request
|
|
6
|
+
from simple_module_core.events import EventBus
|
|
7
|
+
from simple_module_db.deps import get_db
|
|
8
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
9
|
+
|
|
10
|
+
from background_tasks.service import BackgroundTaskService
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
async def get_background_task_service(
|
|
14
|
+
request: Request,
|
|
15
|
+
db: AsyncSession = Depends(get_db),
|
|
16
|
+
) -> BackgroundTaskService:
|
|
17
|
+
services = request.app.state.background_tasks
|
|
18
|
+
bus: EventBus = request.app.state.sm.event_bus
|
|
19
|
+
return BackgroundTaskService(db=db, celery=services.celery, event_bus=bus)
|
|
File without changes
|