django-tasks-db-pool 0.0.2__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.
- django_tasks_db_pool-0.0.2/PKG-INFO +77 -0
- django_tasks_db_pool-0.0.2/README.md +41 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/__init__.py +5 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/app_logger.py +12 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/apps.py +11 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/backoff.py +49 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/db_adapter.py +214 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/db_coordinator.py +247 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/label.py +1 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/management/__init__.py +0 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/management/commands/__init__.py +0 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/management/commands/db_pool_worker.py +241 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/messages.py +47 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/pool_health.py +79 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/pool_runner.py +143 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/process_worker.py +137 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/processes.py +1 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/runner_registry.py +37 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/signals.py +40 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/task_executor.py +81 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/task_tracker.py +177 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/__init__.py +62 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/datetime.py +45 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/tags.py +25 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/timedelta.py +44 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/uuid.py +23 -0
- django_tasks_db_pool-0.0.2/django_tasks_db_pool/wire_types/values.py +113 -0
- django_tasks_db_pool-0.0.2/docs/architecture.md +39 -0
- django_tasks_db_pool-0.0.2/docs/configuration.md +52 -0
- django_tasks_db_pool-0.0.2/docs/deployment.md +36 -0
- django_tasks_db_pool-0.0.2/docs/lifecycle.md +20 -0
- django_tasks_db_pool-0.0.2/pyproject.toml +111 -0
- django_tasks_db_pool-0.0.2/pyproject.toml.orig +96 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: django-tasks-db-pool
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: A multi-process, multi-threaded worker pool for django-tasks-db
|
|
5
|
+
Keywords: django,tasks,db_pool_worker,background-jobs,multiprocessing,asyncio
|
|
6
|
+
Author: tcely
|
|
7
|
+
Author-email: tcely <tcely@users.noreply.github.com>
|
|
8
|
+
License-Expression: BSD-3-Clause
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Environment :: No Input/Output (Daemon)
|
|
12
|
+
Classifier: Framework :: Django
|
|
13
|
+
Classifier: Framework :: Django :: 6.0
|
|
14
|
+
Classifier: Framework :: Django :: 6.1
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Intended Audience :: Information Technology
|
|
17
|
+
Classifier: Intended Audience :: System Administrators
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
26
|
+
Classifier: Topic :: Other/Nonlisted Topic
|
|
27
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
28
|
+
Requires-Dist: django>=6.0
|
|
29
|
+
Requires-Dist: django-tasks-db
|
|
30
|
+
Requires-Python: >=3.12
|
|
31
|
+
Project-URL: Homepage, https://pypi.org/project/django-tasks-db-pool/
|
|
32
|
+
Project-URL: Documentation, https://pypi.org/project/django-tasks-db-pool/
|
|
33
|
+
Project-URL: Repository, https://github.com/tcely/django-tasks-db-pool
|
|
34
|
+
Project-URL: Issues, https://github.com/tcely/django-tasks-db-pool/issues
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# django-tasks-db-pool
|
|
38
|
+
|
|
39
|
+
A multi-process, multi-threaded worker pool for [`django-tasks-db`](docs/architecture.md) designed for Django 6.0+ and Python 3.12+.
|
|
40
|
+
|
|
41
|
+
## Features
|
|
42
|
+
|
|
43
|
+
- **Single database coordinator thread**: Eliminates multi-worker lock contention by centralizing task claims, status writes, and `WorkerStatus` heartbeats on one database connection.
|
|
44
|
+
- **Lazy, ramping task claims**: Starts at one claim per process and grows by three per completed task up to `--workers`, never claiming work without a free thread.
|
|
45
|
+
- **Unified sync & async execution**: Runs `async def` tasks on persistent per-thread `asyncio.Runner` event loops and executes synchronous tasks directly on worker threads.
|
|
46
|
+
- **Huey-style exponential polling backoff**: Backs off smoothly (`interval * backoff ** attempts`) when idle and resets immediately on activity.
|
|
47
|
+
- **Graceful & forced shutdown**: Returns unstarted queued tasks to `READY`, gives running tasks `--grace-timeout` seconds to finish on the first signal, and marks remaining tasks `FAILED` on timeout or a second signal.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install django-tasks-db-pool
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Add both apps to `INSTALLED_APPS`:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
INSTALLED_APPS = [
|
|
59
|
+
# ...
|
|
60
|
+
'django_tasks_db',
|
|
61
|
+
'django_tasks_db_pool',
|
|
62
|
+
]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Quick Start
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
python manage.py db_pool_worker --processes 2 --workers 8
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Documentation
|
|
72
|
+
|
|
73
|
+
- [CLI Options & Configuration](docs/configuration.md)
|
|
74
|
+
- [Pool Architecture & Execution Model](docs/architecture.md)
|
|
75
|
+
- [Shutdown, Signals & Crash Recovery](docs/lifecycle.md)
|
|
76
|
+
- [Deployment & Healthchecks](docs/deployment.md)
|
|
77
|
+
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# django-tasks-db-pool
|
|
2
|
+
|
|
3
|
+
A multi-process, multi-threaded worker pool for [`django-tasks-db`](docs/architecture.md) designed for Django 6.0+ and Python 3.12+.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Single database coordinator thread**: Eliminates multi-worker lock contention by centralizing task claims, status writes, and `WorkerStatus` heartbeats on one database connection.
|
|
8
|
+
- **Lazy, ramping task claims**: Starts at one claim per process and grows by three per completed task up to `--workers`, never claiming work without a free thread.
|
|
9
|
+
- **Unified sync & async execution**: Runs `async def` tasks on persistent per-thread `asyncio.Runner` event loops and executes synchronous tasks directly on worker threads.
|
|
10
|
+
- **Huey-style exponential polling backoff**: Backs off smoothly (`interval * backoff ** attempts`) when idle and resets immediately on activity.
|
|
11
|
+
- **Graceful & forced shutdown**: Returns unstarted queued tasks to `READY`, gives running tasks `--grace-timeout` seconds to finish on the first signal, and marks remaining tasks `FAILED` on timeout or a second signal.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install django-tasks-db-pool
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Add both apps to `INSTALLED_APPS`:
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
INSTALLED_APPS = [
|
|
23
|
+
# ...
|
|
24
|
+
'django_tasks_db',
|
|
25
|
+
'django_tasks_db_pool',
|
|
26
|
+
]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
python manage.py db_pool_worker --processes 2 --workers 8
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Documentation
|
|
36
|
+
|
|
37
|
+
- [CLI Options & Configuration](docs/configuration.md)
|
|
38
|
+
- [Pool Architecture & Execution Model](docs/architecture.md)
|
|
39
|
+
- [Shutdown, Signals & Crash Recovery](docs/lifecycle.md)
|
|
40
|
+
- [Deployment & Healthchecks](docs/deployment.md)
|
|
41
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Self
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(slots=True)
|
|
9
|
+
class PollingBackoff(Iterator[tuple[float, bool]]):
|
|
10
|
+
"""
|
|
11
|
+
Iterable Huey-style exponential polling backoff:
|
|
12
|
+
- Computes `min(max_delay, initial_delay * (backoff ** attempts))`.
|
|
13
|
+
- `next(backoff)` yields `(delay_seconds, hit_max_delay)` and increments attempts.
|
|
14
|
+
- `backoff.reset()` resets attempts back to 0 immediately on activity.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
initial_delay: float = 0.1
|
|
18
|
+
backoff: float = 1.15
|
|
19
|
+
max_delay: float = 20.0
|
|
20
|
+
_attempts: int = 0
|
|
21
|
+
|
|
22
|
+
def __iter__(self) -> Self:
|
|
23
|
+
return self
|
|
24
|
+
|
|
25
|
+
def __next__(self) -> tuple[float, bool]:
|
|
26
|
+
delay = self.current_delay
|
|
27
|
+
hit_max = delay >= self.max_delay
|
|
28
|
+
if not hit_max:
|
|
29
|
+
self._attempts += 1
|
|
30
|
+
return delay, hit_max
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def attempts(self) -> int:
|
|
34
|
+
return self._attempts
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def current_delay(self) -> float:
|
|
38
|
+
if self.initial_delay <= 0:
|
|
39
|
+
return 0.0
|
|
40
|
+
if self.backoff <= 1.0 or self._attempts <= 0:
|
|
41
|
+
return min(self.max_delay, self.initial_delay)
|
|
42
|
+
return min(self.max_delay, self.initial_delay * (self.backoff ** self._attempts)) # fmt: skip
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def is_at_max(self) -> bool:
|
|
46
|
+
return self.current_delay >= self.max_delay
|
|
47
|
+
|
|
48
|
+
def reset(self) -> None:
|
|
49
|
+
self._attempts = 0
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from django.core.exceptions import SuspiciousOperation
|
|
7
|
+
from django.db.utils import OperationalError
|
|
8
|
+
from django.utils import timezone
|
|
9
|
+
from django_tasks_db.backend import TaskResult
|
|
10
|
+
from django_tasks_db.compat import (
|
|
11
|
+
task_backends,
|
|
12
|
+
task_finished,
|
|
13
|
+
task_started,
|
|
14
|
+
)
|
|
15
|
+
from django_tasks_db.models import DBTaskResult
|
|
16
|
+
from django_tasks_db.utils import (
|
|
17
|
+
exclusive_transaction,
|
|
18
|
+
is_locked_database_exception,
|
|
19
|
+
retry,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .app_logger import logger
|
|
23
|
+
from .messages import WorkItem
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ClaimedTaskHandle:
|
|
27
|
+
"""
|
|
28
|
+
Wraps a claimed DBTaskResult so the coordinator thread can extract its
|
|
29
|
+
callable/arguments and persist SUCCEEDED, FAILED, or READY transitions cleanly.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, db_task_result: DBTaskResult[..., Any]) -> None:
|
|
33
|
+
self.db_result = db_task_result
|
|
34
|
+
task = self.db_result.task
|
|
35
|
+
task_result = self.db_result.task_result
|
|
36
|
+
|
|
37
|
+
self.id = task_result.id
|
|
38
|
+
self.context = task.takes_context
|
|
39
|
+
self.func = task.func
|
|
40
|
+
self.module_path = task.module_path
|
|
41
|
+
self.args = tuple(task_result.args)
|
|
42
|
+
self.kwargs = dict(task_result.kwargs)
|
|
43
|
+
|
|
44
|
+
def notify_started(self) -> None:
|
|
45
|
+
task = self.db_result.task
|
|
46
|
+
task_result = self.db_result.task_result
|
|
47
|
+
|
|
48
|
+
backend_type = type(task.get_backend())
|
|
49
|
+
task_started.send(sender=backend_type, task_result=task_result)
|
|
50
|
+
|
|
51
|
+
def mark_successful(self, return_value: Any) -> None:
|
|
52
|
+
task = self.db_result.task
|
|
53
|
+
task_result = self.db_result.task_result
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
self.db_result.set_successful(return_value)
|
|
57
|
+
except BaseException as exc:
|
|
58
|
+
self.mark_failed(exc)
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
backend_type = type(task.get_backend())
|
|
62
|
+
task_finished.send(sender=backend_type, task_result=task_result)
|
|
63
|
+
|
|
64
|
+
def mark_failed(self, exc: BaseException) -> None:
|
|
65
|
+
self.db_result.set_failed(exc)
|
|
66
|
+
try:
|
|
67
|
+
task = self.db_result.task
|
|
68
|
+
task_result = self.db_result.task_result
|
|
69
|
+
backend_type = type(task.get_backend())
|
|
70
|
+
except (ImportError, SuspiciousOperation):
|
|
71
|
+
logger.exception('Task id=%s failed unexpectedly', self.db_result.id)
|
|
72
|
+
else:
|
|
73
|
+
task_finished.send(sender=backend_type, task_result=task_result)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class DatabaseTaskAdapter:
|
|
77
|
+
"""
|
|
78
|
+
Provides atomic task claiming and shutdown relinquishing on the single
|
|
79
|
+
database coordinator thread.
|
|
80
|
+
|
|
81
|
+
Snapshots the backend's configured queues at startup so unconfigured or
|
|
82
|
+
retired queues in the database are never claimed.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
*,
|
|
88
|
+
backend_name: str,
|
|
89
|
+
queue_names: list[str],
|
|
90
|
+
excluded_queue_names: list[str],
|
|
91
|
+
worker_id: str,
|
|
92
|
+
) -> None:
|
|
93
|
+
self.backend_name = backend_name
|
|
94
|
+
self.worker_id = worker_id
|
|
95
|
+
|
|
96
|
+
backend = task_backends[backend_name]
|
|
97
|
+
configured_queues = set(backend.queues)
|
|
98
|
+
|
|
99
|
+
if '*' in queue_names:
|
|
100
|
+
candidate_queues = configured_queues
|
|
101
|
+
else:
|
|
102
|
+
requested = set(queue_names)
|
|
103
|
+
unknown = requested - configured_queues
|
|
104
|
+
if unknown:
|
|
105
|
+
logger.warning(
|
|
106
|
+
'Ignoring unconfigured queue(s) for backend %r: %s',
|
|
107
|
+
backend_name,
|
|
108
|
+
', '.join(sorted(unknown)),
|
|
109
|
+
)
|
|
110
|
+
candidate_queues = requested & configured_queues
|
|
111
|
+
|
|
112
|
+
self.effective_queues = sorted(candidate_queues - set(excluded_queue_names))
|
|
113
|
+
if not self.effective_queues:
|
|
114
|
+
logger.warning(
|
|
115
|
+
'No configured queues remain to process for backend %r.',
|
|
116
|
+
backend_name,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def claim_next_task(self) -> ClaimedTaskHandle | None:
|
|
120
|
+
if not self.effective_queues:
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
tasks = DBTaskResult.objects.ready().filter(
|
|
124
|
+
backend_name=self.backend_name,
|
|
125
|
+
queue_name__in=self.effective_queues,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
with exclusive_transaction(tasks.db):
|
|
129
|
+
try:
|
|
130
|
+
db_task_result = tasks.get_locked()
|
|
131
|
+
if db_task_result is None:
|
|
132
|
+
return None
|
|
133
|
+
db_task_result.claim(self.worker_id)
|
|
134
|
+
except OperationalError as exc:
|
|
135
|
+
if is_locked_database_exception(exc):
|
|
136
|
+
return None
|
|
137
|
+
raise
|
|
138
|
+
|
|
139
|
+
handle = ClaimedTaskHandle(db_task_result)
|
|
140
|
+
handle.notify_started()
|
|
141
|
+
return handle
|
|
142
|
+
|
|
143
|
+
def relinquish_task(self, handle: ClaimedTaskHandle) -> None:
|
|
144
|
+
"""Revert an unstarted claimed task back to READY on shutdown."""
|
|
145
|
+
claimed = handle.db_result
|
|
146
|
+
claim_field_names = {'started_at', 'status'}
|
|
147
|
+
retry_save = retry(retries=5)(claimed.save)
|
|
148
|
+
|
|
149
|
+
claimed.refresh_from_db()
|
|
150
|
+
for field_name in claim_field_names:
|
|
151
|
+
default = None
|
|
152
|
+
field = claimed._meta.get_field(field_name)
|
|
153
|
+
if callable(get_default := getattr(field, 'get_default', None)):
|
|
154
|
+
default = get_default()
|
|
155
|
+
setattr(claimed, field_name, default)
|
|
156
|
+
|
|
157
|
+
claimed.worker_ids = [wid for wid in claimed.worker_ids if wid != self.worker_id]
|
|
158
|
+
claim_field_names.add('worker_ids')
|
|
159
|
+
retry_save(update_fields=claim_field_names)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def create_task_result(item: WorkItem) -> TaskResult[..., Any]:
|
|
163
|
+
return DBTaskResult(
|
|
164
|
+
id=item.task_id,
|
|
165
|
+
status=item.status,
|
|
166
|
+
enqueued_at=datetime.datetime.fromisoformat(item.enqueued_at)
|
|
167
|
+
if item.enqueued_at
|
|
168
|
+
else timezone.now(),
|
|
169
|
+
started_at=datetime.datetime.fromisoformat(item.started_at) if item.started_at else None,
|
|
170
|
+
finished_at=datetime.datetime.fromisoformat(item.finished_at) if item.finished_at else None,
|
|
171
|
+
args_kwargs=dict(
|
|
172
|
+
args=list(item.args),
|
|
173
|
+
kwargs=item.kwargs,
|
|
174
|
+
),
|
|
175
|
+
priority=item.priority,
|
|
176
|
+
task_path=item.task_path,
|
|
177
|
+
worker_ids=item.worker_ids,
|
|
178
|
+
queue_name=item.queue,
|
|
179
|
+
backend_name=item.backend,
|
|
180
|
+
run_after=datetime.datetime.fromisoformat(item.run_after)
|
|
181
|
+
if item.run_after
|
|
182
|
+
else timezone.now(),
|
|
183
|
+
).task_result
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def create_work_item(task_record: ClaimedTaskHandle) -> WorkItem:
|
|
187
|
+
db_result = task_record.db_result
|
|
188
|
+
task_result = db_result.task_result
|
|
189
|
+
|
|
190
|
+
return WorkItem(
|
|
191
|
+
task_id=task_record.id,
|
|
192
|
+
task_path=str(db_result.task_path),
|
|
193
|
+
args=tuple(task_record.args),
|
|
194
|
+
context=bool(task_record.context),
|
|
195
|
+
kwargs=dict(task_record.kwargs),
|
|
196
|
+
attempts=int(task_result.attempts or 0),
|
|
197
|
+
backend=str(db_result.backend_name),
|
|
198
|
+
enqueued_at=str()
|
|
199
|
+
if task_result.enqueued_at is None
|
|
200
|
+
else task_result.enqueued_at.isoformat(),
|
|
201
|
+
errors=task_result.errors or list(),
|
|
202
|
+
finished_at=str()
|
|
203
|
+
if task_result.finished_at is None
|
|
204
|
+
else task_result.finished_at.isoformat(),
|
|
205
|
+
last_attempted_at=str()
|
|
206
|
+
if task_result.last_attempted_at is None
|
|
207
|
+
else task_result.last_attempted_at.isoformat(),
|
|
208
|
+
priority=int(db_result.priority or 0),
|
|
209
|
+
queue=str(db_result.queue_name),
|
|
210
|
+
run_after=str() if db_result.run_after is None else db_result.run_after.isoformat(),
|
|
211
|
+
started_at=str() if task_result.started_at is None else task_result.started_at.isoformat(),
|
|
212
|
+
status=str(db_result.status),
|
|
213
|
+
worker_ids=task_result.worker_ids or list(),
|
|
214
|
+
)
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import multiprocessing as mp
|
|
4
|
+
import queue
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from concurrent.futures import Future, ProcessPoolExecutor
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from django.db import close_old_connections
|
|
12
|
+
from django_tasks_db.worker_status import WorkerStatus
|
|
13
|
+
|
|
14
|
+
from .app_logger import logger
|
|
15
|
+
from .backoff import PollingBackoff
|
|
16
|
+
from .messages import EventKind, WorkEvent
|
|
17
|
+
from .pool_health import check_and_recover_workers
|
|
18
|
+
from .task_tracker import InFlightTaskTracker
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _is_result_event(ev: WorkEvent) -> bool:
|
|
22
|
+
return ev.kind in (
|
|
23
|
+
EventKind.SUCCEEDED,
|
|
24
|
+
EventKind.FAILED,
|
|
25
|
+
EventKind.REQUEUE,
|
|
26
|
+
EventKind.RELINQUISH,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _drain_events(
|
|
31
|
+
event_queue: Any,
|
|
32
|
+
tracker: InFlightTaskTracker,
|
|
33
|
+
is_stopping: bool,
|
|
34
|
+
) -> tuple[int, bool]:
|
|
35
|
+
"""Drain all queued worker events, returning `(total_events, had_result_event)`."""
|
|
36
|
+
processed = 0
|
|
37
|
+
had_result = False
|
|
38
|
+
while True:
|
|
39
|
+
try:
|
|
40
|
+
ev: WorkEvent = event_queue.get_nowait()
|
|
41
|
+
except queue.Empty:
|
|
42
|
+
break
|
|
43
|
+
tracker.handle_event(ev, is_stopping)
|
|
44
|
+
processed += 1
|
|
45
|
+
if _is_result_event(ev):
|
|
46
|
+
had_result = True
|
|
47
|
+
return processed, had_result
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _wait_for_event(
|
|
51
|
+
event_queue: Any,
|
|
52
|
+
tracker: InFlightTaskTracker,
|
|
53
|
+
timeout: float,
|
|
54
|
+
is_stopping: bool,
|
|
55
|
+
) -> tuple[bool, bool]:
|
|
56
|
+
"""Wait up to `timeout` for a worker event, returning `(got_event, is_result_event)`."""
|
|
57
|
+
try:
|
|
58
|
+
ev: WorkEvent = event_queue.get(timeout=timeout)
|
|
59
|
+
except queue.Empty:
|
|
60
|
+
return False, False
|
|
61
|
+
tracker.handle_event(ev, is_stopping)
|
|
62
|
+
return True, _is_result_event(ev)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def database_thread_loop(
|
|
66
|
+
stop_event: threading.Event,
|
|
67
|
+
force_event: threading.Event,
|
|
68
|
+
shutdown_event: Any,
|
|
69
|
+
task_queue: Any,
|
|
70
|
+
event_queue: Any,
|
|
71
|
+
process_pool_holder: list[ProcessPoolExecutor],
|
|
72
|
+
worker_futures: dict[int, Future[None]],
|
|
73
|
+
claim_next_task: Callable[[], Any | None],
|
|
74
|
+
relinquish_task: Callable[[Any], None],
|
|
75
|
+
status: WorkerStatus,
|
|
76
|
+
on_pool_ready: Callable[[], None] | None,
|
|
77
|
+
num_processes: int,
|
|
78
|
+
total_workers: int,
|
|
79
|
+
ctx: mp.context.BaseContext,
|
|
80
|
+
grace_timeout: float = 30.0,
|
|
81
|
+
initial_delay: float = 0.1,
|
|
82
|
+
backoff_factor: float = 1.15,
|
|
83
|
+
max_delay: float = 10.0,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""
|
|
86
|
+
Single database coordinator thread in the command process:
|
|
87
|
+
- Waits for all worker processes to report WORKER_READY before marking started.
|
|
88
|
+
- Starts at 1 claim per process (`num_processes`) and grows by 3 per result
|
|
89
|
+
(`+1` freed slot + `2` new slots) until reaching `total_workers`.
|
|
90
|
+
- Iterates `PollingBackoff` on idle polls and resets on activity.
|
|
91
|
+
- Pings `WorkerStatus` immediately on incoming results or when reaching `max_delay`.
|
|
92
|
+
"""
|
|
93
|
+
tracker = InFlightTaskTracker(
|
|
94
|
+
total_capacity=total_workers,
|
|
95
|
+
initial_limit=num_processes,
|
|
96
|
+
num_processes=num_processes,
|
|
97
|
+
task_queue=task_queue,
|
|
98
|
+
relinquish_task=relinquish_task,
|
|
99
|
+
)
|
|
100
|
+
backoff = PollingBackoff(
|
|
101
|
+
initial_delay=initial_delay,
|
|
102
|
+
backoff=backoff_factor,
|
|
103
|
+
max_delay=max_delay,
|
|
104
|
+
)
|
|
105
|
+
shutdown_deadline: float | None = None
|
|
106
|
+
ready_notified = False
|
|
107
|
+
|
|
108
|
+
def record_activity(should_ping: bool) -> None:
|
|
109
|
+
backoff.reset()
|
|
110
|
+
if should_ping and ready_notified:
|
|
111
|
+
status.ping()
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
while not stop_event.is_set() or tracker:
|
|
115
|
+
is_stopping = stop_event.is_set()
|
|
116
|
+
|
|
117
|
+
drained_count, had_result = _drain_events(event_queue, tracker, is_stopping)
|
|
118
|
+
if drained_count > 0:
|
|
119
|
+
record_activity(should_ping=had_result)
|
|
120
|
+
|
|
121
|
+
if is_stopping:
|
|
122
|
+
if shutdown_deadline is None:
|
|
123
|
+
shutdown_event.set()
|
|
124
|
+
shutdown_deadline = time.monotonic() + grace_timeout
|
|
125
|
+
|
|
126
|
+
tracker.drain_unstarted_queue()
|
|
127
|
+
check_and_recover_workers(
|
|
128
|
+
process_pool_holder,
|
|
129
|
+
worker_futures,
|
|
130
|
+
tracker,
|
|
131
|
+
task_queue,
|
|
132
|
+
event_queue,
|
|
133
|
+
shutdown_event,
|
|
134
|
+
num_processes,
|
|
135
|
+
total_workers,
|
|
136
|
+
ctx,
|
|
137
|
+
is_stopping=True,
|
|
138
|
+
is_forced=force_event.is_set(),
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
if not tracker:
|
|
142
|
+
break
|
|
143
|
+
|
|
144
|
+
if force_event.is_set():
|
|
145
|
+
logger.warning(
|
|
146
|
+
'Forced shutdown requested; failing %d running task(s)',
|
|
147
|
+
len(tracker),
|
|
148
|
+
)
|
|
149
|
+
abort_exc = SystemExit('Worker shutdown forced by second signal')
|
|
150
|
+
for tid in tracker.all_active_ids():
|
|
151
|
+
tracker.mark_failed(tid, abort_exc)
|
|
152
|
+
break
|
|
153
|
+
|
|
154
|
+
remaining_grace = shutdown_deadline - time.monotonic()
|
|
155
|
+
if remaining_grace <= 0:
|
|
156
|
+
logger.warning(
|
|
157
|
+
'Graceful shutdown timed out after %.2fs; failing %d running task(s)',
|
|
158
|
+
grace_timeout,
|
|
159
|
+
len(tracker),
|
|
160
|
+
)
|
|
161
|
+
timeout_exc = TimeoutError(
|
|
162
|
+
f'Task aborted after {grace_timeout}s graceful shutdown timeout'
|
|
163
|
+
)
|
|
164
|
+
for tid in tracker.all_active_ids():
|
|
165
|
+
tracker.mark_failed(tid, timeout_exc)
|
|
166
|
+
break
|
|
167
|
+
|
|
168
|
+
got_event, is_result = _wait_for_event(
|
|
169
|
+
event_queue,
|
|
170
|
+
tracker,
|
|
171
|
+
timeout=min(max_delay, remaining_grace),
|
|
172
|
+
is_stopping=True,
|
|
173
|
+
)
|
|
174
|
+
if got_event and is_result and ready_notified:
|
|
175
|
+
status.ping()
|
|
176
|
+
continue
|
|
177
|
+
|
|
178
|
+
if not ready_notified:
|
|
179
|
+
for slot, wf in worker_futures.items():
|
|
180
|
+
if wf.done():
|
|
181
|
+
exc = wf.exception()
|
|
182
|
+
raise RuntimeError(
|
|
183
|
+
f'Worker process slot {slot} failed during startup: {exc!r}'
|
|
184
|
+
) from exc
|
|
185
|
+
|
|
186
|
+
if tracker.is_pool_ready:
|
|
187
|
+
if on_pool_ready is not None:
|
|
188
|
+
on_pool_ready()
|
|
189
|
+
ready_notified = True
|
|
190
|
+
else:
|
|
191
|
+
_wait_for_event(
|
|
192
|
+
event_queue,
|
|
193
|
+
tracker,
|
|
194
|
+
timeout=min(0.1, max_delay),
|
|
195
|
+
is_stopping=False,
|
|
196
|
+
)
|
|
197
|
+
continue
|
|
198
|
+
|
|
199
|
+
check_and_recover_workers(
|
|
200
|
+
process_pool_holder,
|
|
201
|
+
worker_futures,
|
|
202
|
+
tracker,
|
|
203
|
+
task_queue,
|
|
204
|
+
event_queue,
|
|
205
|
+
shutdown_event,
|
|
206
|
+
num_processes,
|
|
207
|
+
total_workers,
|
|
208
|
+
ctx,
|
|
209
|
+
is_stopping=False,
|
|
210
|
+
is_forced=False,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
if not tracker.try_acquire_slot():
|
|
214
|
+
got_event, is_result = _wait_for_event(
|
|
215
|
+
event_queue, tracker, max_delay, is_stopping=False
|
|
216
|
+
)
|
|
217
|
+
if got_event:
|
|
218
|
+
record_activity(should_ping=is_result)
|
|
219
|
+
else:
|
|
220
|
+
status.ping()
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
close_old_connections()
|
|
224
|
+
task_record = claim_next_task()
|
|
225
|
+
|
|
226
|
+
if task_record is None:
|
|
227
|
+
tracker.release_slot()
|
|
228
|
+
wait_delay, hit_max = next(backoff)
|
|
229
|
+
if hit_max:
|
|
230
|
+
status.ping()
|
|
231
|
+
|
|
232
|
+
got_event, is_result = _wait_for_event(
|
|
233
|
+
event_queue, tracker, wait_delay, is_stopping=False
|
|
234
|
+
)
|
|
235
|
+
if got_event:
|
|
236
|
+
record_activity(should_ping=is_result)
|
|
237
|
+
continue
|
|
238
|
+
|
|
239
|
+
backoff.reset()
|
|
240
|
+
tracker.dispatch(task_record)
|
|
241
|
+
finally:
|
|
242
|
+
tracker.drain_unstarted_queue()
|
|
243
|
+
if tracker:
|
|
244
|
+
abort_exc = SystemExit('Worker shutdown forced')
|
|
245
|
+
for remaining_id in tracker.all_active_ids():
|
|
246
|
+
tracker.mark_failed(remaining_id, abort_exc)
|
|
247
|
+
close_old_connections()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
LABEL = 'django_tasks_db_pool'
|
|
File without changes
|
|
File without changes
|