django-tasks-db-pool 0.0.2__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,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .pool_runner import run_worker_pool
4
+
5
+ __all__ = ['run_worker_pool']
@@ -0,0 +1,12 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ from django_tasks_db.compat import TASKS_LOGGER
6
+
7
+ from .label import LABEL
8
+
9
+ POOL_LOGGER = LABEL
10
+
11
+ logger = logging.getLogger(POOL_LOGGER)
12
+ tasks_logger = logging.getLogger(TASKS_LOGGER)
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from django.apps import AppConfig
4
+
5
+ from .label import LABEL
6
+
7
+
8
+ class TasksDBPoolAppConfig(AppConfig):
9
+ name = 'django_tasks_db_pool'
10
+ label = LABEL
11
+ verbose_name = 'Tasks Database Backend Worker Pool'
@@ -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