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,243 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Task Status Module
|
|
3
|
+
|
|
4
|
+
This module provides the task status management functionality,
|
|
5
|
+
including task state representation and transition handling.
|
|
6
|
+
"""
|
|
7
|
+
import asyncio
|
|
8
|
+
import logging
|
|
9
|
+
import time
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from typing import Any, Dict, Optional
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, Field, ConfigDict, field_validator, PrivateAttr
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TaskStatus(str, Enum):
|
|
20
|
+
"""
|
|
21
|
+
Enumeration of possible task states.
|
|
22
|
+
|
|
23
|
+
Using string enum ensures JSON-serializable values.
|
|
24
|
+
"""
|
|
25
|
+
PENDING = "pending"
|
|
26
|
+
RUNNING = "running"
|
|
27
|
+
COMPLETED = "completed"
|
|
28
|
+
FAILED = "failed"
|
|
29
|
+
CANCELLED = "cancelled"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ProgressUpdateStrategy:
|
|
33
|
+
"""
|
|
34
|
+
Controls how progress updates are throttled and managed.
|
|
35
|
+
|
|
36
|
+
Instead of acquiring a lock for every update, this class implements
|
|
37
|
+
a rate-limited approach to progress tracking.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self,
|
|
41
|
+
min_update_interval: float = 0.1, # Minimum time between updates in seconds
|
|
42
|
+
min_progress_change: float = 0.02, # Minimum change in progress to trigger an update
|
|
43
|
+
):
|
|
44
|
+
self.min_update_interval = min_update_interval
|
|
45
|
+
self.min_progress_change = min_progress_change
|
|
46
|
+
self.last_update_time = 0.0
|
|
47
|
+
self.last_progress_value = 0.0
|
|
48
|
+
|
|
49
|
+
def should_update(self, new_progress: float) -> bool:
|
|
50
|
+
"""
|
|
51
|
+
Determine if a progress update should be processed.
|
|
52
|
+
|
|
53
|
+
Uses a combination of time-based throttling and value-based delta checking.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
new_progress: The new progress value (0.0 to 1.0)
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
True if the update should be processed, False otherwise
|
|
60
|
+
"""
|
|
61
|
+
current_time = time.time()
|
|
62
|
+
time_since_update = current_time - self.last_update_time
|
|
63
|
+
progress_change = abs(new_progress - self.last_progress_value)
|
|
64
|
+
|
|
65
|
+
# Always update if this is the first update (time=0)
|
|
66
|
+
if self.last_update_time == 0.0:
|
|
67
|
+
self.last_update_time = current_time
|
|
68
|
+
self.last_progress_value = new_progress
|
|
69
|
+
return True
|
|
70
|
+
|
|
71
|
+
# Always update on completion (progress=1.0)
|
|
72
|
+
if new_progress == 1.0 and self.last_progress_value != 1.0:
|
|
73
|
+
self.last_update_time = current_time
|
|
74
|
+
self.last_progress_value = new_progress
|
|
75
|
+
return True
|
|
76
|
+
|
|
77
|
+
# Check if enough time has passed or enough progress has been made
|
|
78
|
+
if (time_since_update >= self.min_update_interval or
|
|
79
|
+
progress_change >= self.min_progress_change):
|
|
80
|
+
self.last_update_time = current_time
|
|
81
|
+
self.last_progress_value = new_progress
|
|
82
|
+
return True
|
|
83
|
+
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TaskInfo(BaseModel):
|
|
88
|
+
"""
|
|
89
|
+
Task information model for tracking task state.
|
|
90
|
+
|
|
91
|
+
Contains all metadata about a task including its current status,
|
|
92
|
+
timestamps, results, and custom metadata.
|
|
93
|
+
"""
|
|
94
|
+
id: str
|
|
95
|
+
status: TaskStatus
|
|
96
|
+
created_at: datetime
|
|
97
|
+
started_at: Optional[datetime] = None
|
|
98
|
+
completed_at: Optional[datetime] = None
|
|
99
|
+
result: Optional[Any] = None
|
|
100
|
+
error: Optional[str] = None
|
|
101
|
+
progress: float = 0.0
|
|
102
|
+
metadata: Dict[str, Any] = Field(default_factory=dict)
|
|
103
|
+
|
|
104
|
+
# Lock for synchronized state changes
|
|
105
|
+
_lock: asyncio.Lock = PrivateAttr(default_factory=asyncio.Lock)
|
|
106
|
+
|
|
107
|
+
# Progress update throttling
|
|
108
|
+
_progress_strategy: ProgressUpdateStrategy = PrivateAttr(default_factory=ProgressUpdateStrategy)
|
|
109
|
+
|
|
110
|
+
# In-progress value for atomic updates
|
|
111
|
+
_current_progress: float = PrivateAttr(default=0.0)
|
|
112
|
+
|
|
113
|
+
# Pydantic v2 configuration
|
|
114
|
+
model_config = ConfigDict(
|
|
115
|
+
arbitrary_types_allowed=True,
|
|
116
|
+
validate_assignment=True,
|
|
117
|
+
extra="allow"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
@field_validator("progress", mode="before")
|
|
121
|
+
def validate_progress(cls, v: float) -> float:
|
|
122
|
+
"""Validate progress range"""
|
|
123
|
+
if v < 0.0:
|
|
124
|
+
return 0.0
|
|
125
|
+
elif v > 1.0:
|
|
126
|
+
return 1.0
|
|
127
|
+
return v
|
|
128
|
+
|
|
129
|
+
def is_terminal_state(self) -> bool:
|
|
130
|
+
"""
|
|
131
|
+
Check if the task is in a terminal state.
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
True if the task is completed, failed, or cancelled
|
|
135
|
+
"""
|
|
136
|
+
return self.status in (TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED)
|
|
137
|
+
|
|
138
|
+
def update_progress(self, progress: float) -> None:
|
|
139
|
+
"""
|
|
140
|
+
Update task progress with throttling and validation.
|
|
141
|
+
This is a lock-free operation that updates the internal progress value.
|
|
142
|
+
The actual progress field update is governed by the ProgressUpdateStrategy.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
progress: Progress value between 0.0 and 1.0
|
|
146
|
+
"""
|
|
147
|
+
# Ensure progress is within bounds
|
|
148
|
+
if progress < 0.0:
|
|
149
|
+
progress = 0.0
|
|
150
|
+
elif progress > 1.0:
|
|
151
|
+
progress = 1.0
|
|
152
|
+
|
|
153
|
+
# Update the atomic progress value
|
|
154
|
+
self._current_progress = progress
|
|
155
|
+
|
|
156
|
+
# If the update strategy says we should update the displayed progress,
|
|
157
|
+
# then update the actual progress field which triggers validation
|
|
158
|
+
if self._progress_strategy.should_update(progress):
|
|
159
|
+
self.progress = progress
|
|
160
|
+
|
|
161
|
+
async def mark_started(self) -> None:
|
|
162
|
+
"""
|
|
163
|
+
Mark the task as started.
|
|
164
|
+
"""
|
|
165
|
+
async with self._lock:
|
|
166
|
+
self.status = TaskStatus.RUNNING
|
|
167
|
+
self.started_at = datetime.now()
|
|
168
|
+
|
|
169
|
+
async def mark_completed(self, result: Any) -> None:
|
|
170
|
+
"""
|
|
171
|
+
Mark the task as successfully completed.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
result: The result of the task
|
|
175
|
+
"""
|
|
176
|
+
async with self._lock:
|
|
177
|
+
if self.is_terminal_state():
|
|
178
|
+
logger.warning(
|
|
179
|
+
f"Task {self.id} is already in a terminal state ({self.status}), cannot mark as completed.")
|
|
180
|
+
return
|
|
181
|
+
self.status = TaskStatus.COMPLETED
|
|
182
|
+
self.completed_at = datetime.now()
|
|
183
|
+
self.result = result
|
|
184
|
+
|
|
185
|
+
# Ensure progress is set to 100% on completion
|
|
186
|
+
self._current_progress = 1.0
|
|
187
|
+
self.progress = 1.0
|
|
188
|
+
|
|
189
|
+
async def mark_failed(self, error: str) -> None:
|
|
190
|
+
"""
|
|
191
|
+
Mark the task as failed.
|
|
192
|
+
|
|
193
|
+
Args:
|
|
194
|
+
error: Error message or exception information
|
|
195
|
+
"""
|
|
196
|
+
async with self._lock:
|
|
197
|
+
self.status = TaskStatus.FAILED
|
|
198
|
+
self.completed_at = datetime.now()
|
|
199
|
+
self.error = error
|
|
200
|
+
|
|
201
|
+
async def mark_cancelled(self, reason: Optional[str] = None) -> None:
|
|
202
|
+
"""
|
|
203
|
+
Mark the task as cancelled.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
reason: Optional reason for cancellation
|
|
207
|
+
"""
|
|
208
|
+
async with self._lock:
|
|
209
|
+
logger.info(f"Marking task {self.id} as cancelled: {reason}")
|
|
210
|
+
self.status = TaskStatus.CANCELLED
|
|
211
|
+
self.completed_at = datetime.now()
|
|
212
|
+
self.error = reason
|
|
213
|
+
|
|
214
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
215
|
+
"""
|
|
216
|
+
Convert task info to a dictionary.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
Dictionary with task information
|
|
220
|
+
"""
|
|
221
|
+
# Use the most up-to-date progress value, even if not yet in .progress
|
|
222
|
+
current_progress = max(self.progress, self._current_progress)
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
"id": self.id,
|
|
226
|
+
"status": self.status.value,
|
|
227
|
+
"created_at": self.created_at.isoformat(),
|
|
228
|
+
"started_at": self.started_at.isoformat() if self.started_at else None,
|
|
229
|
+
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
|
|
230
|
+
"result": self.result,
|
|
231
|
+
"error": self.error,
|
|
232
|
+
"progress": current_progress,
|
|
233
|
+
"metadata": self.metadata,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
def get_current_progress(self) -> float:
|
|
237
|
+
"""
|
|
238
|
+
Get the most up-to-date progress value, including any pending updates.
|
|
239
|
+
|
|
240
|
+
Returns:
|
|
241
|
+
The current progress as a float between 0.0 and 1.0
|
|
242
|
+
"""
|
|
243
|
+
return max(self.progress, self._current_progress)
|