simple-module-background-tasks 0.0.1__py3-none-any.whl

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.
@@ -0,0 +1,105 @@
1
+ """Internal Celery tasks registered by the background_tasks module itself.
2
+
3
+ - ``sweep_stuck_tasks`` flips ``running`` rows whose heartbeat has gone stale
4
+ to ``stuck`` so the UI surfaces them and they become eligible for retry.
5
+ - ``purge_old_executions`` deletes terminal rows older than the configured
6
+ retention so the history table stays bounded.
7
+
8
+ Both are driven by Celery beat; see :mod:`.celery_app`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ from datetime import UTC, datetime, timedelta
16
+
17
+ from celery import shared_task
18
+ from sqlalchemy import delete, update
19
+
20
+ from background_tasks.constants import (
21
+ DEFAULT_RETENTION_DAYS,
22
+ DEFAULT_STUCK_AFTER_SECONDS,
23
+ DEMO_ECHO_TASK,
24
+ INTERNAL_TASK_PURGE_OLD,
25
+ INTERNAL_TASK_SWEEP_STUCK,
26
+ TERMINAL_STATUSES,
27
+ TaskStatus,
28
+ )
29
+ from background_tasks.models import TaskExecution
30
+ from background_tasks.settings import BackgroundTasksSettings
31
+ from background_tasks.sync_db import sync_session
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ def _load_settings() -> BackgroundTasksSettings:
37
+ """Build settings inside the worker process.
38
+
39
+ The web-process ``register_settings`` attached them to ``app.state``,
40
+ but the worker never sees that ``app.state``. Re-parsing from env here
41
+ is the same deterministic source of truth.
42
+ """
43
+ return BackgroundTasksSettings()
44
+
45
+
46
+ @shared_task(name=DEMO_ECHO_TASK)
47
+ def demo_echo(message: str = "hello") -> dict[str, str]:
48
+ """Trivial task used for end-to-end smoke tests of the Celery pipeline.
49
+
50
+ Returns the input wrapped with a worker timestamp so a successful
51
+ execution produces a non-empty ``result`` column in the admin UI.
52
+ """
53
+ logger.info("demo_echo received message=%r", message)
54
+ return {"message": message, "at": datetime.now(UTC).isoformat()}
55
+
56
+
57
+ @shared_task(name=INTERNAL_TASK_SWEEP_STUCK)
58
+ def sweep_stuck_tasks() -> int:
59
+ """Flip ``running`` rows with stale heartbeats to ``stuck``.
60
+
61
+ Returns the number of rows flipped — handy for metrics/log scraping.
62
+ """
63
+ # Avoid import-time coupling to settings (beat schedules this task
64
+ # before the worker has hydrated settings in some edge cases).
65
+ stuck_after = int(
66
+ os.environ.get("SM_BG_TASKS_STUCK_AFTER_SECONDS", DEFAULT_STUCK_AFTER_SECONDS)
67
+ )
68
+ cutoff = datetime.now(UTC) - timedelta(seconds=stuck_after)
69
+
70
+ with sync_session() as session:
71
+ stmt = (
72
+ update(TaskExecution)
73
+ .where(
74
+ TaskExecution.status == TaskStatus.RUNNING,
75
+ TaskExecution.heartbeat_at < cutoff,
76
+ )
77
+ .values(status=TaskStatus.STUCK, finished_at=datetime.now(UTC))
78
+ )
79
+ result = session.execute(stmt)
80
+ count = result.rowcount or 0
81
+ if count:
82
+ logger.warning("sweep_stuck_tasks flipped %d row(s) to stuck", count)
83
+ return count
84
+
85
+
86
+ @shared_task(name=INTERNAL_TASK_PURGE_OLD)
87
+ def purge_old_executions() -> int:
88
+ """Delete terminal rows older than the retention window."""
89
+ retention_days = int(os.environ.get("SM_BG_TASKS_RETENTION_DAYS", DEFAULT_RETENTION_DAYS))
90
+ cutoff = datetime.now(UTC) - timedelta(days=retention_days)
91
+
92
+ with sync_session() as session:
93
+ result = session.execute(
94
+ delete(TaskExecution)
95
+ .where(TaskExecution.status.in_(list(TERMINAL_STATUSES)))
96
+ .where(TaskExecution.finished_at < cutoff)
97
+ )
98
+ count = result.rowcount or 0
99
+ if count:
100
+ logger.info(
101
+ "purge_old_executions removed %d row(s) older than %d days",
102
+ count,
103
+ retention_days,
104
+ )
105
+ return count
@@ -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,33 @@
1
+ background_tasks/__init__.py,sha256=60_v6M-VjBdOGQ4fcXqol8-Y3I5Jks1FGW28HYicjdM,74
2
+ background_tasks/_signal_support.py,sha256=lVkUJVETou-6JbNx0PWYUYftuxDZHJdK8m0usPlE7sk,3592
3
+ background_tasks/celery_app.py,sha256=wYJ_lYJhL47eKRTra5YXRTViGEmUvFD1vonhsBzBSUc,3637
4
+ background_tasks/constants.py,sha256=hU1ixbdDO2ljrRVSl8GtffTZ5jmev6gyQ61lK5IWbio,3622
5
+ background_tasks/deps.py,sha256=lIeYAF1LpH1V0TmA1En837dctwG1Us9ofj9Mao4XFN4,640
6
+ background_tasks/models.py,sha256=03LFc5Mwwt1b2YIXxsqC5eJabGqY0daMaXq7SwctINo,3119
7
+ background_tasks/module.py,sha256=cjigSk2NLw5q6Q6tNNiCk0SZH2alm4FKMSzm_P8-Gt4,4167
8
+ background_tasks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ background_tasks/service.py,sha256=SGqxmX4qcU5Lxlp1ryc-lK8YBXCwQl6KB_KJBaonGWE,4629
10
+ background_tasks/services.py,sha256=qcozJCqz-uk-l3B0ia2nbAMVJlnRMpB8qqQABBPtap4,719
11
+ background_tasks/settings.py,sha256=cfhxR29OVPFf4efec9v_JhcHfXYh1x-J-Y6Pe43RG5k,3476
12
+ background_tasks/signals.py,sha256=-U55iJZWi8olA7xgXEXXFhIiyVce1hAVka7RVAI1E34,9028
13
+ background_tasks/sync_db.py,sha256=yCsaMTlVh6-ts4-SVudwjaGozy4ldkIdC0DSQiHSzgQ,2713
14
+ background_tasks/tasks.py,sha256=i_XKnLsFh4bol-p1RYw5O7LmzYL5aZkZ2W6bxckoBT0,3656
15
+ background_tasks/contracts/__init__.py,sha256=sqrpzp0NbQstATtJL9DeZEPHCZCbAA1kGAI1ws4ONU8,55
16
+ background_tasks/contracts/events.py,sha256=03pbS_ZuD1PR_psChc9s847IGS3Q91njf5XLgkE7wtM,561
17
+ background_tasks/contracts/schemas.py,sha256=YCoYjc_IoMw_E3IL6h8bNkj7ju_nn23qgUHPGeyo40k,1766
18
+ background_tasks/endpoints/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ background_tasks/endpoints/api_admin.py,sha256=YQIDdfUID2grjHifQ3xbSuiBb6yW1PB5FlVXJuSmkM8,1993
20
+ background_tasks/endpoints/views.py,sha256=B5LNvuQ5uhJgGhaOJk5IQEBvWHTOKloxHhRxz_amCeI,2140
21
+ background_tasks/locales/en.json,sha256=T2EZWSVf26winxDH3f-cBOCpnNDff5Hj4Xqs5NMm4W8,1576
22
+ background_tasks/pages/Detail.tsx,sha256=6ED26ixYl5PPoKvAegJAfA-7HwcJdXdK-hdDbttiWlI,6279
23
+ background_tasks/pages/Index.tsx,sha256=g7dIR733475v9UxkYyXI6VMYX3Ot8Mrn_il5FyuksvY,6341
24
+ background_tasks/pages/constants.ts,sha256=lQCkUOcq7rwRWj2xHxdvMZH7KAx4RJuPK9CgfCcg2eg,1357
25
+ background_tasks/pages/retry.ts,sha256=duQKWwZm4Q5WEXrT9m3XQHU_qBVg8MIGldFQSkXzHd4,1280
26
+ background_tasks/pages/components/ExecutionRow.tsx,sha256=emw_NWVXgjZzsS7n5NgygogvZr4OIrby02l_21EUHTg,2911
27
+ background_tasks/pages/components/RetryConfirmDialog.tsx,sha256=DLW_5V8SahdBdsUEtMMOQ4575S0oPzknA1UjhCcoO5s,1118
28
+ background_tasks/package.json,sha256=CPFVBDyd3BL5Y1903hPyTOeLBoVeeiIQsDBDqZgAIcg,394
29
+ simple_module_background_tasks-0.0.1.dist-info/METADATA,sha256=KFE6tswrIg9Kw0ayoj9Sn93vxuhxR70Mh3HuipI5n_A,3142
30
+ simple_module_background_tasks-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
31
+ simple_module_background_tasks-0.0.1.dist-info/entry_points.txt,sha256=b3_GVa5rtiTO0l6bM04dIXQNT208aQ48BGFVqwhbXxs,81
32
+ simple_module_background_tasks-0.0.1.dist-info/licenses/LICENSE,sha256=Yn66lhLklsF5p7pa85_ksQrJ79Q-FgOaUAHevLBjer4,1068
33
+ simple_module_background_tasks-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [simple_module]
2
+ background_tasks = background_tasks.module:BackgroundTasksModule
@@ -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.