async-task-worker 0.3.0__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.
- async_cache/__init__.py +83 -0
- async_cache/adapters/__init__.py +11 -0
- async_cache/adapters/memory.py +122 -0
- async_cache/adapters/redis.py +182 -0
- async_cache/core.py +680 -0
- async_cache/exceptions.py +16 -0
- async_cache/key_utils.py +136 -0
- async_cache/serialization.py +230 -0
- async_task_worker/__init__.py +93 -0
- async_task_worker/adapters/__init__.py +3 -0
- async_task_worker/adapters/cache_adapter.py +206 -0
- async_task_worker/api.py +371 -0
- async_task_worker/core.py +717 -0
- async_task_worker/exceptions.py +245 -0
- async_task_worker/executor.py +204 -0
- async_task_worker/futures.py +232 -0
- async_task_worker/pool.py +343 -0
- async_task_worker/queue.py +265 -0
- async_task_worker/registry.py +96 -0
- async_task_worker/status.py +243 -0
- async_task_worker-0.3.0.dist-info/METADATA +1144 -0
- async_task_worker-0.3.0.dist-info/RECORD +24 -0
- async_task_worker-0.3.0.dist-info/WHEEL +4 -0
- async_task_worker-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Worker Pool Module
|
|
3
|
+
|
|
4
|
+
This module manages the pool of worker tasks that process
|
|
5
|
+
items from the task queue.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import logging
|
|
10
|
+
import time
|
|
11
|
+
from typing import Callable, Dict, List, Optional, Self, Any, Awaitable, TypeVar
|
|
12
|
+
|
|
13
|
+
from async_task_worker.executor import TaskExecutor
|
|
14
|
+
from async_task_worker.queue import TaskQueue
|
|
15
|
+
from async_task_worker.status import TaskInfo
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
# Type definitions
|
|
20
|
+
T = TypeVar('T') # Used for generic task function return type
|
|
21
|
+
|
|
22
|
+
# Define a type for task status update callback
|
|
23
|
+
TaskStatusCallback = Callable[[str, Optional[TaskInfo], Any], Awaitable[None]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class WorkerPool:
|
|
27
|
+
"""
|
|
28
|
+
Manages a pool of worker tasks that process items from a task queue.
|
|
29
|
+
|
|
30
|
+
Focuses solely on worker lifecycle management and task execution,
|
|
31
|
+
delegating state management to callbacks.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
task_queue: TaskQueue,
|
|
37
|
+
task_executor: TaskExecutor,
|
|
38
|
+
max_workers: int = 10,
|
|
39
|
+
worker_poll_interval: float = 1.0,
|
|
40
|
+
on_task_start: Optional[TaskStatusCallback] = None,
|
|
41
|
+
on_task_complete: Optional[TaskStatusCallback] = None,
|
|
42
|
+
on_task_failed: Optional[TaskStatusCallback] = None,
|
|
43
|
+
on_task_cancelled: Optional[TaskStatusCallback] = None,
|
|
44
|
+
):
|
|
45
|
+
"""
|
|
46
|
+
Initialize the worker pool.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
task_queue: Queue to get tasks from
|
|
50
|
+
task_executor: Executor for running tasks
|
|
51
|
+
max_workers: Maximum number of concurrent workers
|
|
52
|
+
worker_poll_interval: How often workers check for new tasks
|
|
53
|
+
on_task_start: Callback when a task starts execution
|
|
54
|
+
on_task_complete: Callback when a task completes successfully
|
|
55
|
+
on_task_failed: Callback when a task fails
|
|
56
|
+
on_task_cancelled: Callback when a task is cancelled
|
|
57
|
+
"""
|
|
58
|
+
self.task_queue = task_queue
|
|
59
|
+
self.task_executor = task_executor
|
|
60
|
+
self.max_workers = max_workers
|
|
61
|
+
self.worker_poll_interval = worker_poll_interval
|
|
62
|
+
|
|
63
|
+
# Callbacks for task state changes
|
|
64
|
+
self.on_task_start = on_task_start
|
|
65
|
+
self.on_task_complete = on_task_complete
|
|
66
|
+
self.on_task_failed = on_task_failed
|
|
67
|
+
self.on_task_cancelled = on_task_cancelled
|
|
68
|
+
|
|
69
|
+
self.workers: List[asyncio.Task] = []
|
|
70
|
+
self.running = False
|
|
71
|
+
self._running_tasks: Dict[str, asyncio.Task] = {}
|
|
72
|
+
self._running_tasks_lock = asyncio.Lock()
|
|
73
|
+
self._task_to_worker: Dict[str, asyncio.Task] = {}
|
|
74
|
+
|
|
75
|
+
async def __aenter__(self) -> Self:
|
|
76
|
+
"""Support async context manager protocol."""
|
|
77
|
+
await self.start()
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
81
|
+
"""Support async context manager protocol."""
|
|
82
|
+
await self.stop()
|
|
83
|
+
|
|
84
|
+
async def start(self) -> None:
|
|
85
|
+
"""Start the worker pool."""
|
|
86
|
+
if self.running:
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
self.running = True
|
|
90
|
+
|
|
91
|
+
# Start worker tasks
|
|
92
|
+
for i in range(self.max_workers):
|
|
93
|
+
worker = asyncio.create_task(self._worker_loop(worker_id=i))
|
|
94
|
+
worker.set_name(f"task_worker_{i}")
|
|
95
|
+
self.workers.append(worker)
|
|
96
|
+
|
|
97
|
+
logger.info(f"Started {self.max_workers} worker tasks")
|
|
98
|
+
|
|
99
|
+
async def stop(self, timeout: float = 5.0) -> None:
|
|
100
|
+
"""
|
|
101
|
+
Stop the worker pool gracefully.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
timeout: Maximum time to wait for tasks to complete
|
|
105
|
+
"""
|
|
106
|
+
if not self.running:
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
self.running = False
|
|
110
|
+
logger.info("Stopping worker pool...")
|
|
111
|
+
|
|
112
|
+
# First cancel all running tasks
|
|
113
|
+
cancelled_tasks = []
|
|
114
|
+
async with self._running_tasks_lock:
|
|
115
|
+
for task_id, task in self._running_tasks.items():
|
|
116
|
+
if not task.done():
|
|
117
|
+
logger.info(f"Cancelling task {task_id}")
|
|
118
|
+
task.cancel()
|
|
119
|
+
cancelled_tasks.append(task_id)
|
|
120
|
+
|
|
121
|
+
# Notify about cancelled tasks via callback
|
|
122
|
+
if self.on_task_cancelled and cancelled_tasks:
|
|
123
|
+
for task_id in cancelled_tasks:
|
|
124
|
+
try:
|
|
125
|
+
await self.on_task_cancelled(task_id, None, "Worker pool shutting down")
|
|
126
|
+
except Exception as e:
|
|
127
|
+
logger.error(f"Error in task cancelled callback for {task_id}: {str(e)}")
|
|
128
|
+
|
|
129
|
+
# Then wait for worker tasks to complete
|
|
130
|
+
if self.workers:
|
|
131
|
+
# First try cooperative cancellation
|
|
132
|
+
for worker in self.workers:
|
|
133
|
+
if not worker.done():
|
|
134
|
+
worker.cancel()
|
|
135
|
+
|
|
136
|
+
# Wait for workers to finish with proper exception handling
|
|
137
|
+
try:
|
|
138
|
+
# Use asyncio.timeout() context manager (Python 3.11+)
|
|
139
|
+
async with asyncio.timeout(timeout):
|
|
140
|
+
pending = list(self.workers)
|
|
141
|
+
# Shield to prevent this wait from being cancelled
|
|
142
|
+
await asyncio.gather(*[asyncio.shield(worker) for worker in pending],
|
|
143
|
+
return_exceptions=True)
|
|
144
|
+
except TimeoutError:
|
|
145
|
+
logger.warning(f"Worker pool stop timed out after {timeout}s")
|
|
146
|
+
# Force cancellation for any remaining workers
|
|
147
|
+
for worker in self.workers:
|
|
148
|
+
if not worker.done():
|
|
149
|
+
worker.cancel()
|
|
150
|
+
|
|
151
|
+
# Give them a moment to finish cancellation
|
|
152
|
+
try:
|
|
153
|
+
async with asyncio.timeout(0.5):
|
|
154
|
+
await asyncio.gather(*[w for w in self.workers if not w.done()],
|
|
155
|
+
return_exceptions=True)
|
|
156
|
+
except (TimeoutError, asyncio.CancelledError):
|
|
157
|
+
pass # Ignore any exceptions here
|
|
158
|
+
except Exception as e:
|
|
159
|
+
logger.error(f"Error during worker shutdown: {str(e)}")
|
|
160
|
+
# Continue with cleanup even if there was an error
|
|
161
|
+
|
|
162
|
+
self.workers = []
|
|
163
|
+
|
|
164
|
+
# Clean up running tasks dictionary
|
|
165
|
+
async with self._running_tasks_lock:
|
|
166
|
+
self._running_tasks.clear()
|
|
167
|
+
self._task_to_worker.clear()
|
|
168
|
+
|
|
169
|
+
logger.info("Worker pool stopped")
|
|
170
|
+
|
|
171
|
+
async def _worker_loop(self, worker_id: int) -> None:
|
|
172
|
+
"""
|
|
173
|
+
Main worker loop that processes tasks from the queue.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
worker_id: Unique identifier for this worker
|
|
177
|
+
"""
|
|
178
|
+
logger.debug(f"Worker {worker_id} started")
|
|
179
|
+
|
|
180
|
+
last_activity = time.time()
|
|
181
|
+
idle_log_interval = 60 # Log idle status once per minute
|
|
182
|
+
|
|
183
|
+
while self.running:
|
|
184
|
+
try:
|
|
185
|
+
# Simplified task processing flow
|
|
186
|
+
task_item = await self._get_next_task(worker_id, last_activity, idle_log_interval)
|
|
187
|
+
if task_item is None:
|
|
188
|
+
continue
|
|
189
|
+
|
|
190
|
+
last_activity = time.time()
|
|
191
|
+
priority, task_id, task_func, task_args, task_kwargs, timeout = task_item
|
|
192
|
+
|
|
193
|
+
# Process the task
|
|
194
|
+
try:
|
|
195
|
+
await self._process_task(worker_id, task_id, task_func, task_args, task_kwargs, timeout)
|
|
196
|
+
finally:
|
|
197
|
+
# Always mark task as done in queue
|
|
198
|
+
self.task_queue.task_done()
|
|
199
|
+
|
|
200
|
+
except asyncio.CancelledError:
|
|
201
|
+
logger.debug(f"Worker {worker_id} cancelled")
|
|
202
|
+
break
|
|
203
|
+
except Exception as e:
|
|
204
|
+
logger.error(f"Unexpected error in worker {worker_id}: {str(e)}", exc_info=True)
|
|
205
|
+
await asyncio.sleep(0.1) # Avoid tight loop on persistent errors
|
|
206
|
+
|
|
207
|
+
logger.debug(f"Worker {worker_id} stopped")
|
|
208
|
+
|
|
209
|
+
async def _get_next_task(self, worker_id, last_activity, idle_log_interval):
|
|
210
|
+
"""Get the next task with timeout and idle logging"""
|
|
211
|
+
try:
|
|
212
|
+
async with asyncio.timeout(self.worker_poll_interval):
|
|
213
|
+
return await self.task_queue.get()
|
|
214
|
+
except TimeoutError:
|
|
215
|
+
# Log idle status if needed
|
|
216
|
+
current_time = time.time()
|
|
217
|
+
if current_time - last_activity > idle_log_interval:
|
|
218
|
+
logger.debug(f"Worker {worker_id} idle for {current_time - last_activity:.1f}s")
|
|
219
|
+
return None
|
|
220
|
+
# Check if we should continue running
|
|
221
|
+
if not self.running:
|
|
222
|
+
logger.debug(f"Worker {worker_id} cancelled due to shutdown")
|
|
223
|
+
raise asyncio.CancelledError()
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
async def _process_task(self, worker_id, task_id, task_func, task_args, task_kwargs, timeout):
|
|
227
|
+
"""Process a single task"""
|
|
228
|
+
logger.info(f"Worker {worker_id} processing task {task_id}")
|
|
229
|
+
|
|
230
|
+
# Get task info from the executor's context if needed
|
|
231
|
+
task_info = None # We don't directly manage TaskInfo anymore
|
|
232
|
+
|
|
233
|
+
# Notify task started
|
|
234
|
+
if self.on_task_start:
|
|
235
|
+
try:
|
|
236
|
+
await self.on_task_start(task_id, task_info, None)
|
|
237
|
+
except Exception as e:
|
|
238
|
+
logger.error(f"Error in task start callback for {task_id}: {str(e)}")
|
|
239
|
+
|
|
240
|
+
# Execute the task
|
|
241
|
+
execution_task = asyncio.create_task(
|
|
242
|
+
self.task_executor.execute_task(
|
|
243
|
+
task_id, None, task_func, task_args, task_kwargs, timeout
|
|
244
|
+
)
|
|
245
|
+
)
|
|
246
|
+
execution_task.set_name(f"exec_{task_id}")
|
|
247
|
+
|
|
248
|
+
# Register running task
|
|
249
|
+
async with self._running_tasks_lock:
|
|
250
|
+
self._running_tasks[task_id] = execution_task
|
|
251
|
+
self._task_to_worker[task_id] = execution_task
|
|
252
|
+
|
|
253
|
+
try:
|
|
254
|
+
result = await execution_task
|
|
255
|
+
|
|
256
|
+
# Notify task completed
|
|
257
|
+
if self.on_task_complete:
|
|
258
|
+
try:
|
|
259
|
+
await self.on_task_complete(task_id, task_info, result)
|
|
260
|
+
except Exception as e:
|
|
261
|
+
logger.error(f"Error in task complete callback for {task_id}: {str(e)}")
|
|
262
|
+
|
|
263
|
+
except asyncio.CancelledError:
|
|
264
|
+
logger.info(f"Task {task_id} execution cancelled")
|
|
265
|
+
|
|
266
|
+
# Notify task cancelled
|
|
267
|
+
if self.on_task_cancelled:
|
|
268
|
+
try:
|
|
269
|
+
await self.on_task_cancelled(task_id, task_info, "Task cancelled during execution")
|
|
270
|
+
except Exception as e:
|
|
271
|
+
logger.error(f"Error in task cancelled callback for {task_id}: {str(e)}")
|
|
272
|
+
raise
|
|
273
|
+
|
|
274
|
+
except Exception as e:
|
|
275
|
+
logger.error(f"Error in task {task_id}: {str(e)}", exc_info=True)
|
|
276
|
+
|
|
277
|
+
# Notify task failed
|
|
278
|
+
if self.on_task_failed:
|
|
279
|
+
try:
|
|
280
|
+
await self.on_task_failed(task_id, task_info, str(e))
|
|
281
|
+
except Exception as callback_error:
|
|
282
|
+
logger.error(f"Error in task failed callback for {task_id}: {str(callback_error)}")
|
|
283
|
+
finally:
|
|
284
|
+
logger.info(f"Task {task_id} finished")
|
|
285
|
+
# Clean up task reference
|
|
286
|
+
async with self._running_tasks_lock:
|
|
287
|
+
if task_id in self._running_tasks:
|
|
288
|
+
del self._running_tasks[task_id]
|
|
289
|
+
if task_id in self._task_to_worker:
|
|
290
|
+
del self._task_to_worker[task_id]
|
|
291
|
+
|
|
292
|
+
async def cancel_running_task(self, task_id: str) -> bool:
|
|
293
|
+
"""
|
|
294
|
+
Cancel a task that is currently running in a worker.
|
|
295
|
+
|
|
296
|
+
This method focuses only on finding and canceling the actual running task
|
|
297
|
+
in asyncio. Task state updates are handled through callbacks.
|
|
298
|
+
|
|
299
|
+
The cancellation process is atomic and thread-safe, ensuring that
|
|
300
|
+
the task state is checked and modified under a lock to prevent race conditions.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
task_id: ID of the task to cancel
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
True if task was found and cancelled, False otherwise
|
|
307
|
+
"""
|
|
308
|
+
logger.info(f"Worker pool attempting to cancel running task {task_id}")
|
|
309
|
+
|
|
310
|
+
async with self._running_tasks_lock:
|
|
311
|
+
# Check if task exists in our tracking dictionaries
|
|
312
|
+
worker_task = self._task_to_worker.get(task_id)
|
|
313
|
+
if not worker_task:
|
|
314
|
+
logger.warning(f"Worker task for {task_id} not found in running tasks")
|
|
315
|
+
return False
|
|
316
|
+
|
|
317
|
+
# Check if task is already done before attempting to cancel
|
|
318
|
+
if worker_task.done():
|
|
319
|
+
logger.info(f"Task {task_id} is already completed, cannot cancel")
|
|
320
|
+
# Remove from tracking
|
|
321
|
+
if task_id in self._running_tasks:
|
|
322
|
+
del self._running_tasks[task_id]
|
|
323
|
+
if task_id in self._task_to_worker:
|
|
324
|
+
del self._task_to_worker[task_id]
|
|
325
|
+
return False
|
|
326
|
+
|
|
327
|
+
# Task exists and is running - cancel it
|
|
328
|
+
logger.info(f"Cancelling running task {task_id}")
|
|
329
|
+
worker_task.cancel()
|
|
330
|
+
|
|
331
|
+
# Task references are cleaned up in the worker task's finally block
|
|
332
|
+
|
|
333
|
+
return True
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def active_tasks_count(self) -> int:
|
|
337
|
+
"""Get the number of currently running tasks."""
|
|
338
|
+
return len(self._running_tasks)
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def worker_count(self) -> int:
|
|
342
|
+
"""Get the current number of workers."""
|
|
343
|
+
return len(self.workers)
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Task Queue with improved cancellation support
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Set
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class QueueStats:
|
|
16
|
+
"""Statistics for the task queue."""
|
|
17
|
+
queue_size: int = 0
|
|
18
|
+
enqueued_total: int = 0
|
|
19
|
+
dequeued_total: int = 0
|
|
20
|
+
avg_wait_time: float = 0.0
|
|
21
|
+
peak_queue_size: int = 0
|
|
22
|
+
last_enqueued_at: Optional[float] = None
|
|
23
|
+
last_dequeued_at: Optional[float] = None
|
|
24
|
+
wait_times: List[float] = field(default_factory=list)
|
|
25
|
+
_wait_time_window: int = 100 # Track last N wait times
|
|
26
|
+
|
|
27
|
+
def update_enqueue(self) -> None:
|
|
28
|
+
"""Update statistics when a task is enqueued."""
|
|
29
|
+
self.enqueued_total += 1
|
|
30
|
+
self.queue_size += 1
|
|
31
|
+
self.peak_queue_size = max(self.peak_queue_size, self.queue_size)
|
|
32
|
+
self.last_enqueued_at = time.time()
|
|
33
|
+
|
|
34
|
+
def update_dequeue(self, wait_time: Optional[float] = None) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Update statistics when a task is dequeued.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
wait_time: Optional wait time to record
|
|
40
|
+
"""
|
|
41
|
+
self.dequeued_total += 1
|
|
42
|
+
self.queue_size -= 1
|
|
43
|
+
self.last_dequeued_at = time.time()
|
|
44
|
+
|
|
45
|
+
# Record wait time if provided
|
|
46
|
+
if wait_time is not None:
|
|
47
|
+
# Maintain a sliding window of wait times
|
|
48
|
+
self.wait_times.append(wait_time)
|
|
49
|
+
if len(self.wait_times) > self._wait_time_window:
|
|
50
|
+
self.wait_times.pop(0)
|
|
51
|
+
|
|
52
|
+
# Update average wait time
|
|
53
|
+
if self.wait_times:
|
|
54
|
+
self.avg_wait_time = sum(self.wait_times) / len(self.wait_times)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class TaskQueue:
|
|
58
|
+
"""
|
|
59
|
+
Priority-based task queue with statistics tracking.
|
|
60
|
+
|
|
61
|
+
Provides an asyncio.PriorityQueue with additional functionality
|
|
62
|
+
for monitoring and managing task queues.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, max_size: Optional[int] = None):
|
|
66
|
+
"""
|
|
67
|
+
Initialize the task queue.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
max_size: Maximum queue size (None for unlimited)
|
|
71
|
+
"""
|
|
72
|
+
self.queue = asyncio.PriorityQueue(maxsize=max_size if max_size is not None else 0)
|
|
73
|
+
self.stats = QueueStats()
|
|
74
|
+
|
|
75
|
+
# Track task entry timestamps with task_id key
|
|
76
|
+
self._task_entry_times: Dict[str, float] = {}
|
|
77
|
+
# Track which task_ids are in the queue
|
|
78
|
+
self._queued_task_ids: Set[str] = set()
|
|
79
|
+
# Track which task_ids are cancelled but still in the queue
|
|
80
|
+
self._cancelled_task_ids: Set[str] = set()
|
|
81
|
+
# Lock for operations on the queue
|
|
82
|
+
self._queue_lock = asyncio.Lock()
|
|
83
|
+
|
|
84
|
+
async def put(
|
|
85
|
+
self,
|
|
86
|
+
priority: int,
|
|
87
|
+
task_id: str,
|
|
88
|
+
task_func: Any,
|
|
89
|
+
args: Tuple,
|
|
90
|
+
kwargs: Dict,
|
|
91
|
+
timeout: Optional[float]
|
|
92
|
+
) -> None:
|
|
93
|
+
"""
|
|
94
|
+
Put a task in the queue.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
priority: Task priority (lower is higher priority)
|
|
98
|
+
task_id: Unique task identifier
|
|
99
|
+
task_func: Function to execute
|
|
100
|
+
args: Positional arguments
|
|
101
|
+
kwargs: Keyword arguments
|
|
102
|
+
timeout: Optional task timeout
|
|
103
|
+
"""
|
|
104
|
+
# Record entry time for wait time calculations
|
|
105
|
+
entry_time = time.time()
|
|
106
|
+
|
|
107
|
+
# Thread-safe update of tracking collections
|
|
108
|
+
async with self._queue_lock:
|
|
109
|
+
self._task_entry_times[task_id] = entry_time
|
|
110
|
+
self._queued_task_ids.add(task_id)
|
|
111
|
+
|
|
112
|
+
# Put the task in the queue
|
|
113
|
+
queue_item = (priority, task_id, task_func, args, kwargs, timeout)
|
|
114
|
+
await self.queue.put(queue_item)
|
|
115
|
+
|
|
116
|
+
# Update statistics
|
|
117
|
+
self.stats.update_enqueue()
|
|
118
|
+
|
|
119
|
+
logger.debug(f"Task {task_id} added to queue with priority {priority}")
|
|
120
|
+
|
|
121
|
+
async def get(self, timeout: Optional[float] = None) -> Tuple:
|
|
122
|
+
"""
|
|
123
|
+
Get a task from the queue.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
timeout: Optional timeout for waiting
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
Tuple of (priority, task_id, task_func, args, kwargs, timeout)
|
|
130
|
+
|
|
131
|
+
Raises:
|
|
132
|
+
asyncio.TimeoutError: If timeout is reached before a task is available
|
|
133
|
+
"""
|
|
134
|
+
# If timeout provided, use asyncio.timeout context manager (Python 3.11+)
|
|
135
|
+
if timeout is not None:
|
|
136
|
+
async with asyncio.timeout(timeout):
|
|
137
|
+
return await self._get_valid_task()
|
|
138
|
+
else:
|
|
139
|
+
return await self._get_valid_task()
|
|
140
|
+
|
|
141
|
+
async def _get_valid_task(self) -> Tuple[int, str, Any, tuple, dict, float | None] | None:
|
|
142
|
+
"""
|
|
143
|
+
Get the next valid task from the queue, skipping cancelled tasks.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
Tuple of (priority, task_id, task_func, args, kwargs, timeout)
|
|
147
|
+
"""
|
|
148
|
+
while True:
|
|
149
|
+
item = await self.queue.get()
|
|
150
|
+
# Explicitly unpack to ensure type correctness
|
|
151
|
+
priority: int = item[0]
|
|
152
|
+
task_id: str = item[1]
|
|
153
|
+
task_func: Any = item[2]
|
|
154
|
+
args: Tuple = item[3]
|
|
155
|
+
kwargs: Dict = item[4]
|
|
156
|
+
task_timeout: Optional[int] = item[5]
|
|
157
|
+
|
|
158
|
+
# Check if this task was cancelled while in queue
|
|
159
|
+
async with self._queue_lock:
|
|
160
|
+
if task_id in self._cancelled_task_ids:
|
|
161
|
+
# Skip this task, it was cancelled
|
|
162
|
+
self._cancelled_task_ids.discard(task_id)
|
|
163
|
+
self.queue.task_done()
|
|
164
|
+
logger.debug(f"Skipping cancelled task {task_id}")
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
# Calculate and record wait time
|
|
168
|
+
wait_time = None
|
|
169
|
+
if task_id in self._task_entry_times:
|
|
170
|
+
entry_time = self._task_entry_times[task_id]
|
|
171
|
+
wait_time = time.time() - entry_time
|
|
172
|
+
logger.debug(f"Task {task_id} waited {wait_time:.3f}s in queue")
|
|
173
|
+
del self._task_entry_times[task_id] # Clean up
|
|
174
|
+
|
|
175
|
+
# Remove from queued set
|
|
176
|
+
self._queued_task_ids.discard(task_id)
|
|
177
|
+
|
|
178
|
+
# Update statistics with wait time
|
|
179
|
+
self.stats.update_dequeue(wait_time)
|
|
180
|
+
|
|
181
|
+
# Return as explicitly typed tuple
|
|
182
|
+
return priority, task_id, task_func, args, kwargs, task_timeout
|
|
183
|
+
|
|
184
|
+
def task_done(self) -> None:
|
|
185
|
+
"""Mark a task as done."""
|
|
186
|
+
self.queue.task_done()
|
|
187
|
+
|
|
188
|
+
async def join(self) -> None:
|
|
189
|
+
"""Wait for all tasks to be processed."""
|
|
190
|
+
await self.queue.join()
|
|
191
|
+
|
|
192
|
+
async def is_task_queued(self, task_id: str) -> bool:
|
|
193
|
+
"""
|
|
194
|
+
Check if a task is currently in the queue.
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
task_id: Task identifier to check
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
True if the task is in the queue, False otherwise
|
|
201
|
+
"""
|
|
202
|
+
async with self._queue_lock:
|
|
203
|
+
return task_id in self._queued_task_ids
|
|
204
|
+
|
|
205
|
+
async def remove_task(self, task_id: str) -> bool:
|
|
206
|
+
"""
|
|
207
|
+
Mark a task as cancelled so it will be skipped when dequeued.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
task_id: Task identifier to remove
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
True if the task was in the queue, False otherwise
|
|
214
|
+
"""
|
|
215
|
+
async with self._queue_lock:
|
|
216
|
+
if task_id not in self._queued_task_ids:
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
# Mark as cancelled and update all tracking data atomically
|
|
220
|
+
self._cancelled_task_ids.add(task_id)
|
|
221
|
+
self._queued_task_ids.discard(task_id)
|
|
222
|
+
|
|
223
|
+
if task_id in self._task_entry_times:
|
|
224
|
+
del self._task_entry_times[task_id]
|
|
225
|
+
|
|
226
|
+
# Update queue statistics - decrease size as this task will be skipped
|
|
227
|
+
self.stats.queue_size -= 1
|
|
228
|
+
|
|
229
|
+
logger.debug(f"Task {task_id} marked for cancellation")
|
|
230
|
+
return True
|
|
231
|
+
|
|
232
|
+
async def clean_cancelled_tasks(self, task_ids: List[str]) -> None:
|
|
233
|
+
"""
|
|
234
|
+
Clean up tracking for a list of task IDs.
|
|
235
|
+
"""
|
|
236
|
+
async with self._queue_lock:
|
|
237
|
+
for task_id in task_ids:
|
|
238
|
+
self._cancelled_task_ids.discard(task_id)
|
|
239
|
+
self._queued_task_ids.discard(task_id)
|
|
240
|
+
if task_id in self._task_entry_times:
|
|
241
|
+
del self._task_entry_times[task_id]
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def qsize(self) -> int:
|
|
245
|
+
"""Get current queue size."""
|
|
246
|
+
return self.queue.qsize()
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def empty(self) -> bool:
|
|
250
|
+
"""Check if queue is empty."""
|
|
251
|
+
return self.queue.empty()
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def full(self) -> bool:
|
|
255
|
+
"""Check if queue is full."""
|
|
256
|
+
return self.queue.full()
|
|
257
|
+
|
|
258
|
+
def clear_tracking(self) -> None:
|
|
259
|
+
"""
|
|
260
|
+
Clear task tracking dictionaries.
|
|
261
|
+
Ensures no memory leaks from cancelled tasks by clearing all tracking data structures.
|
|
262
|
+
"""
|
|
263
|
+
self._task_entry_times.clear()
|
|
264
|
+
self._queued_task_ids.clear()
|
|
265
|
+
self._cancelled_task_ids.clear()
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Task Registry System
|
|
3
|
+
|
|
4
|
+
This module provides a task registration system with manual registration.
|
|
5
|
+
"""
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
import threading
|
|
9
|
+
from functools import wraps
|
|
10
|
+
from typing import Any, Awaitable, Callable, Dict, List, Optional, TypeVar
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
# Type definitions
|
|
15
|
+
T = TypeVar('T') # Used for generic task function return type
|
|
16
|
+
TaskFunc = Callable[..., Awaitable[T]]
|
|
17
|
+
|
|
18
|
+
# Global task registry
|
|
19
|
+
_TASK_REGISTRY: Dict[str, TaskFunc] = {}
|
|
20
|
+
|
|
21
|
+
# Use a standard threading lock for synchronous operations
|
|
22
|
+
_REGISTRY_LOCK = threading.RLock()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def task(task_type: str) -> Callable[[TaskFunc], TaskFunc]:
|
|
26
|
+
"""
|
|
27
|
+
Decorator to register a function as a task handler.
|
|
28
|
+
|
|
29
|
+
Example:
|
|
30
|
+
@task("process_data")
|
|
31
|
+
async def process_data_task(data: dict, config: dict) -> dict:
|
|
32
|
+
# Process data
|
|
33
|
+
return result
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def decorator(func: TaskFunc) -> TaskFunc:
|
|
37
|
+
# Call synchronous register_task
|
|
38
|
+
# We can't await an async function in a decorator
|
|
39
|
+
register_task(task_type, func)
|
|
40
|
+
|
|
41
|
+
@wraps(func)
|
|
42
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
43
|
+
return await func(*args, **kwargs)
|
|
44
|
+
|
|
45
|
+
return wrapper
|
|
46
|
+
|
|
47
|
+
return decorator
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def register_task(task_type: str, task_func: TaskFunc) -> None:
|
|
51
|
+
"""
|
|
52
|
+
Register a task function for a specific task type (synchronous version).
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
task_type: Unique identifier for the task type
|
|
56
|
+
task_func: Async function that implements the task
|
|
57
|
+
"""
|
|
58
|
+
if not task_type or not isinstance(task_type, str):
|
|
59
|
+
raise ValueError("Task type must be a non-empty string")
|
|
60
|
+
|
|
61
|
+
# Ensure task_func is an async function
|
|
62
|
+
if not inspect.iscoroutinefunction(task_func):
|
|
63
|
+
raise TypeError(f"Task function for {task_type} must be an async function")
|
|
64
|
+
|
|
65
|
+
# Use the threading lock for thread-safe registry updates
|
|
66
|
+
with _REGISTRY_LOCK:
|
|
67
|
+
if task_type in _TASK_REGISTRY:
|
|
68
|
+
logger.warning(f"Overriding existing task handler for {task_type}")
|
|
69
|
+
_TASK_REGISTRY[task_type] = task_func
|
|
70
|
+
|
|
71
|
+
logger.info(f"Registered task handler for {task_type}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def get_task_function(task_type: str) -> Optional[TaskFunc]:
|
|
75
|
+
"""
|
|
76
|
+
Get the task function for a specific task type.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
task_type: The task type to look up
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
The task function or None if not found
|
|
83
|
+
"""
|
|
84
|
+
# No need for locks for read operations on simple dictionary lookup
|
|
85
|
+
return _TASK_REGISTRY.get(task_type)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def get_all_task_types() -> List[str]:
|
|
89
|
+
"""
|
|
90
|
+
Get a list of all registered task types.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List of registered task type names
|
|
94
|
+
"""
|
|
95
|
+
# No need for locks for read operations on a simple list copy
|
|
96
|
+
return list(_TASK_REGISTRY.keys())
|