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.
@@ -0,0 +1,245 @@
1
+ """
2
+ Error Handler Module
3
+
4
+ This module provides a unified error hierarchy for the task worker system.
5
+ """
6
+
7
+ import asyncio
8
+ import logging
9
+ import traceback
10
+ from enum import Enum
11
+ from typing import Any, Dict, Optional
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class ErrorCategory(str, Enum):
17
+ """Categories of errors for classification and handling."""
18
+ TASK_DEFINITION = "task_definition"
19
+ TASK_EXECUTION = "task_execution"
20
+ TIMEOUT = "timeout"
21
+ CANCELLATION = "cancellation"
22
+ RESOURCE = "resource"
23
+ VALIDATION = "validation"
24
+ INTERNAL = "internal"
25
+ UNKNOWN = "unknown"
26
+
27
+
28
+ class SerializationError(Exception):
29
+ """Exception raised when serialization fails."""
30
+ pass
31
+
32
+
33
+ class TaskError(Exception):
34
+ """Base exception for all task worker errors."""
35
+
36
+ def __init__(
37
+ self,
38
+ message: str,
39
+ category: ErrorCategory = ErrorCategory.UNKNOWN,
40
+ original_error: Optional[Exception] = None,
41
+ task_id: Optional[str] = None,
42
+ is_retryable: bool = False
43
+ ):
44
+ self.message = message
45
+ self.category = category
46
+ self.original_error = original_error
47
+ self.task_id = task_id
48
+ self.is_retryable = is_retryable
49
+ super().__init__(message)
50
+
51
+ def __str__(self) -> str:
52
+ base_msg = f"[{self.category}] {self.message}"
53
+ if self.task_id:
54
+ base_msg = f"Task {self.task_id}: {base_msg}"
55
+ return base_msg
56
+
57
+ def to_dict(self) -> Dict[str, Any]:
58
+ """Convert error to a dictionary representation."""
59
+ result = {
60
+ "message": self.message,
61
+ "category": self.category,
62
+ "is_retryable": self.is_retryable,
63
+ }
64
+
65
+ if self.task_id:
66
+ result["task_id"] = self.task_id
67
+
68
+ if self.original_error:
69
+ result["original_error"] = str(self.original_error)
70
+ result["original_type"] = type(self.original_error).__name__
71
+
72
+ return result
73
+
74
+
75
+ class TaskDefinitionError(TaskError):
76
+ """Error in task definition or registration."""
77
+
78
+ def __init__(self, message: str, original_error: Optional[Exception] = None, task_id: Optional[str] = None):
79
+ super().__init__(
80
+ message=message,
81
+ category=ErrorCategory.TASK_DEFINITION,
82
+ original_error=original_error,
83
+ task_id=task_id,
84
+ is_retryable=False
85
+ )
86
+
87
+
88
+ class TaskExecutionError(TaskError):
89
+ """Error during task execution."""
90
+
91
+ def __init__(
92
+ self,
93
+ message: str,
94
+ original_error: Optional[Exception] = None,
95
+ task_id: Optional[str] = None,
96
+ is_retryable: bool = True
97
+ ):
98
+ super().__init__(
99
+ message=message,
100
+ category=ErrorCategory.TASK_EXECUTION,
101
+ original_error=original_error,
102
+ task_id=task_id,
103
+ is_retryable=is_retryable
104
+ )
105
+
106
+
107
+ class TaskTimeoutError(TaskError):
108
+ """Error when a task times out."""
109
+
110
+ def __init__(self, timeout: float, task_id: Optional[str] = None):
111
+ super().__init__(
112
+ message=f"Task timed out after {timeout} seconds",
113
+ category=ErrorCategory.TIMEOUT,
114
+ task_id=task_id,
115
+ is_retryable=True
116
+ )
117
+
118
+
119
+ class TaskCancellationError(TaskError):
120
+ """Error when a task is cancelled."""
121
+
122
+ def __init__(self, message: str = "Task was cancelled", task_id: Optional[str] = None):
123
+ super().__init__(
124
+ message=message,
125
+ category=ErrorCategory.CANCELLATION,
126
+ task_id=task_id,
127
+ is_retryable=False
128
+ )
129
+
130
+
131
+ class ErrorHandler:
132
+ """
133
+ Centralized error handler for task worker.
134
+
135
+ Provides consistent error handling, logging, and categorization.
136
+ """
137
+
138
+ def __init__(self, structured_logging: bool = False):
139
+ """
140
+ Initialize the error handler.
141
+
142
+ Args:
143
+ structured_logging: Whether to use structured logging format
144
+ """
145
+ self.structured_logging = structured_logging
146
+
147
+ def handle_error(
148
+ self,
149
+ error: Exception,
150
+ task_id: Optional[str] = None,
151
+ context: Optional[Dict[str, Any]] = None
152
+ ) -> TaskError:
153
+ """
154
+ Handle an error and return a standardized TaskError.
155
+
156
+ Args:
157
+ error: The exception that occurred
158
+ task_id: Optional task ID for context
159
+ context: Additional context information
160
+
161
+ Returns:
162
+ Standardized TaskError instance
163
+ """
164
+ # Default context if none provided
165
+ if context is None:
166
+ context = {}
167
+
168
+ # If already a TaskError, just add task_id if needed
169
+ if isinstance(error, TaskError):
170
+ if task_id and not error.task_id:
171
+ error.task_id = task_id
172
+ self._log_error(error, context)
173
+ return error
174
+
175
+ # Map standard exceptions to appropriate TaskError types
176
+ if isinstance(error, asyncio.TimeoutError):
177
+ task_error = TaskTimeoutError(
178
+ timeout=context.get("timeout", 0),
179
+ task_id=task_id
180
+ )
181
+ elif isinstance(error, asyncio.CancelledError):
182
+ task_error = TaskCancellationError(task_id=task_id)
183
+ elif isinstance(error, (TypeError, ValueError, AttributeError)):
184
+ task_error = TaskDefinitionError(
185
+ message=str(error),
186
+ original_error=error,
187
+ task_id=task_id
188
+ )
189
+ else:
190
+ # Default to generic execution error
191
+ task_error = TaskExecutionError(
192
+ message=str(error),
193
+ original_error=error,
194
+ task_id=task_id
195
+ )
196
+
197
+ self._log_error(task_error, context)
198
+ return task_error
199
+
200
+ def _log_error(self, error: TaskError, context: Dict[str, Any]) -> None:
201
+ """
202
+ Log an error with appropriate level and format.
203
+
204
+ Args:
205
+ error: The error to log
206
+ context: Additional context information
207
+ """
208
+ # Determine log level based on category
209
+ if error.category in (ErrorCategory.CANCELLATION, ErrorCategory.TIMEOUT):
210
+ log_level = logging.INFO
211
+ elif error.category == ErrorCategory.VALIDATION:
212
+ log_level = logging.WARNING
213
+ else:
214
+ log_level = logging.ERROR
215
+
216
+ # Create log message
217
+ if self.structured_logging:
218
+ log_data = {
219
+ "error": error.to_dict(),
220
+ "context": context
221
+ }
222
+ logger.log(log_level, log_data)
223
+ else:
224
+ message = str(error)
225
+ if error.original_error and log_level >= logging.ERROR:
226
+ logger.log(log_level, message, exc_info=error.original_error)
227
+ else:
228
+ logger.log(log_level, message)
229
+
230
+ @staticmethod
231
+ def format_exception(exc: Exception) -> str:
232
+ """
233
+ Format an exception with traceback into a string.
234
+
235
+ Args:
236
+ exc: The exception to format
237
+
238
+ Returns:
239
+ Formatted exception string with traceback
240
+ """
241
+ if exc.__traceback__:
242
+ tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
243
+ return ''.join(tb_lines)
244
+ else:
245
+ return f"{type(exc).__name__}: {str(exc)}"
@@ -0,0 +1,204 @@
1
+ """
2
+ Task Executor Module with improved type annotations
3
+
4
+ This module handles the execution of tasks, including timeouts,
5
+ error handling, and progress reporting.
6
+ """
7
+
8
+ import asyncio
9
+ import inspect
10
+ import logging
11
+ import time
12
+ from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, TypeVar, Protocol, runtime_checkable
13
+
14
+ from async_task_worker.exceptions import TaskCancellationError, TaskExecutionError, TaskTimeoutError
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
+
23
+ @runtime_checkable
24
+ class ProgressCallback(Protocol):
25
+ """Type protocol for progress callback functions"""
26
+
27
+ def __call__(self, progress: float) -> None: ...
28
+
29
+
30
+ class CacheManager(Protocol):
31
+ """Type protocol for cache manager"""
32
+ enabled: bool
33
+
34
+ async def get(self, func_name: str, args: Tuple, kwargs: Dict) -> Tuple[bool, Any]: ...
35
+
36
+ async def set(
37
+ self,
38
+ func_name: str,
39
+ args: Tuple,
40
+ kwargs: Dict,
41
+ result: Any,
42
+ ttl: Optional[int] = None
43
+ ) -> bool: ...
44
+
45
+
46
+ class TaskExecutor:
47
+ """
48
+ Handles the execution of tasks with proper error handling,
49
+ timeout management, and progress reporting.
50
+ """
51
+
52
+ def __init__(self, cache_manager: Optional[CacheManager] = None):
53
+ """
54
+ Initialize the task executor.
55
+
56
+ Args:
57
+ cache_manager: Optional cache manager for task results
58
+ """
59
+ self.cache_manager = cache_manager
60
+
61
+ async def execute_task(
62
+ self,
63
+ task_id: str,
64
+ task_info: Optional[TaskInfo],
65
+ task_func: Callable[..., Awaitable[T]],
66
+ args: Tuple,
67
+ kwargs: Dict[str, Any],
68
+ timeout: Optional[float] = None
69
+ ) -> T:
70
+ """
71
+ Execute a task with timeout and error handling.
72
+
73
+ Args:
74
+ task_id: Unique task identifier
75
+ task_info: Task information object
76
+ task_func: Function to execute
77
+ args: Positional arguments
78
+ kwargs: Keyword arguments
79
+ timeout: Optional timeout in seconds
80
+
81
+ Returns:
82
+ Task execution result
83
+
84
+ Raises:
85
+ TaskExecutionError: If task execution fails
86
+ TaskTimeoutError: If task times out
87
+ TaskCancellationError: If task is cancelled
88
+ """
89
+ start_time = time.time()
90
+
91
+ # Ensure task_func is a coroutine function
92
+ if not inspect.iscoroutinefunction(task_func):
93
+ error_msg = f"Task {task_id}: Function {task_func.__name__} is not a coroutine function"
94
+ logger.error(error_msg)
95
+ raise TypeError(error_msg)
96
+
97
+ # Extract cache options from kwargs if present
98
+ use_cache: bool = kwargs.pop("use_cache", True)
99
+ cache_ttl: Optional[int] = kwargs.pop("cache_ttl", None)
100
+
101
+ # Try to get from cache if caching is enabled
102
+ if use_cache and self.cache_manager and self.cache_manager.enabled:
103
+ try:
104
+ func_name = task_func.__name__
105
+ # Make a copy without progress_callback for cache key
106
+ cache_kwargs = {k: v for k, v in kwargs.items()
107
+ if k != "progress_callback"}
108
+
109
+ cache_hit, cached_result = await self.cache_manager.get(func_name, args, cache_kwargs)
110
+
111
+ if cache_hit:
112
+ logger.info(f"Task {task_id} using cached result")
113
+ return cached_result
114
+ except Exception as e:
115
+ error_msg = f"Cache retrieval error for task {task_id}: {str(e)}"
116
+ logger.error(error_msg,
117
+ extra={
118
+ "task_id": task_id,
119
+ "function": task_func.__name__,
120
+ "error_type": type(e).__name__,
121
+ "cache_operation": "get"
122
+ },
123
+ exc_info=True)
124
+
125
+ # Don't use cache for this task anymore since retrieval failed
126
+ use_cache = False
127
+
128
+ # Continue execution without caching as a fallback strategy
129
+ # raise TaskExecutionError(f"Cache retrieval failed: {error_msg}", original_error=e, task_id=task_id)
130
+
131
+ # Create a progress callback
132
+ def progress_callback(progress: float) -> None:
133
+ # Validate progress
134
+ if progress < 0.0:
135
+ progress = 0.0
136
+ elif progress > 1.0:
137
+ progress = 1.0
138
+ # If task_info is provided, update it directly
139
+ if task_info is not None:
140
+ task_info.update_progress(progress)
141
+
142
+ # Add progress callback to kwargs if the function accepts it
143
+ task_kwargs_copy = kwargs.copy()
144
+ try:
145
+ # Get the signature and check if it has **kwargs or explicit progress_callback
146
+ sig = inspect.signature(task_func)
147
+ has_progress_param = "progress_callback" in sig.parameters
148
+ has_kwargs = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())
149
+
150
+ # Only add if the function can accept it
151
+ if has_progress_param or has_kwargs:
152
+ task_kwargs_copy["progress_callback"] = progress_callback
153
+ except (ValueError, TypeError) as e:
154
+ logger.warning(f"Could not inspect function signature for {task_func.__name__}: {str(e)}")
155
+ # If we can't inspect the function, don't add the callback
156
+
157
+ # Create task coroutine
158
+ task_coroutine = task_func(*args, **task_kwargs_copy)
159
+
160
+ try:
161
+ # Execute the task with timeout if specified
162
+ if timeout is not None:
163
+ async with asyncio.timeout(timeout):
164
+ result = await task_coroutine
165
+ else:
166
+ result = await task_coroutine
167
+
168
+ # Store in cache if enabled
169
+ if use_cache and self.cache_manager and self.cache_manager.enabled:
170
+ try:
171
+ func_name = task_func.__name__
172
+ cache_kwargs = {k: v for k, v in kwargs.items()
173
+ if k != "progress_callback"}
174
+ await self.cache_manager.set(func_name, args, cache_kwargs, result, cache_ttl)
175
+ except Exception as e:
176
+ error_msg = f"Error caching result for task {task_id}: {str(e)}"
177
+ logger.error(error_msg,
178
+ extra={
179
+ "task_id": task_id,
180
+ "function": task_func.__name__,
181
+ "error_type": type(e).__name__,
182
+ "cache_operation": "set",
183
+ "ttl": cache_ttl
184
+ },
185
+ exc_info=True)
186
+ # Continue and return the result even if caching fails
187
+
188
+ execution_time = time.time() - start_time
189
+ logger.info(f"Task {task_id} completed successfully in {execution_time:.3f}s")
190
+
191
+ return result
192
+
193
+ except TimeoutError:
194
+ logger.error(f"Task {task_id} timed out after {timeout}s")
195
+ raise TaskTimeoutError(timeout, task_id=task_id)
196
+
197
+ except asyncio.CancelledError:
198
+ logger.info(f"Task {task_id} was cancelled")
199
+ raise TaskCancellationError("Task cancelled", task_id=task_id)
200
+
201
+ except Exception as e:
202
+ error_msg = str(e)
203
+ logger.error(f"Task {task_id} failed: {error_msg}", exc_info=True)
204
+ raise TaskExecutionError(f"Task execution failed: {error_msg}", original_error=e, task_id=task_id)
@@ -0,0 +1,232 @@
1
+ """
2
+ Task Futures Module
3
+
4
+ This module provides functionality for tracking task completion
5
+ through asyncio futures.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+ import weakref
11
+ from typing import Self, Set
12
+
13
+ from async_task_worker.exceptions import TaskCancellationError, TaskExecutionError
14
+ from async_task_worker.status import TaskInfo, TaskStatus
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class TaskFutureManager:
20
+ """
21
+ Manages futures for task completion.
22
+
23
+ Uses standard asyncio primitives to track task completion with
24
+ proper memory management through weak references.
25
+ """
26
+
27
+ def __init__(self):
28
+ """Initialize the task future manager."""
29
+ # Only store futures in the weak dictionary to prevent memory leaks
30
+ self._futures = weakref.WeakValueDictionary()
31
+
32
+ # Keep a set of task_ids with pending futures for more efficient iteration
33
+ self._pending_tasks: Set[str] = set()
34
+
35
+ # Lock for synchronization
36
+ self._futures_lock = asyncio.Lock()
37
+
38
+ # Cleanup interval in seconds
39
+ self._cleanup_interval = 60.0
40
+ self._cleanup_task = None
41
+
42
+ async def __aenter__(self) -> Self:
43
+ """Support async context manager protocol."""
44
+ self._start_cleanup_task()
45
+ return self
46
+
47
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
48
+ """Support async context manager protocol."""
49
+ await self.cancel_all_futures()
50
+ self._stop_cleanup_task()
51
+
52
+ def _start_cleanup_task(self) -> None:
53
+ """Start the periodic cleanup task if not already running."""
54
+ if self._cleanup_task is None or self._cleanup_task.done():
55
+ self._cleanup_task = asyncio.create_task(self._periodic_cleanup())
56
+ self._cleanup_task.set_name("future_manager_cleanup")
57
+
58
+ def _stop_cleanup_task(self) -> None:
59
+ """Stop the periodic cleanup task if running."""
60
+ if self._cleanup_task and not self._cleanup_task.done():
61
+ self._cleanup_task.cancel()
62
+
63
+ async def _periodic_cleanup(self) -> None:
64
+ """Periodically clean up completed or lost futures."""
65
+ try:
66
+ while True:
67
+ await asyncio.sleep(self._cleanup_interval)
68
+ await self._cleanup_completed_futures()
69
+ except asyncio.CancelledError:
70
+ logger.debug("Future manager cleanup task cancelled")
71
+ except Exception as e:
72
+ logger.error(f"Error in future manager cleanup task: {e}", exc_info=True)
73
+
74
+ async def _cleanup_completed_futures(self) -> None:
75
+ """Clean up completed futures from the pending tasks set."""
76
+ async with self._futures_lock:
77
+ to_remove = set()
78
+ for task_id in self._pending_tasks:
79
+ # Check if the future exists and is done or has been garbage collected
80
+ future = self._futures.get(task_id)
81
+ if future is None or future.done():
82
+ to_remove.add(task_id)
83
+
84
+ # Remove completed tasks from the pending set
85
+ self._pending_tasks -= to_remove
86
+
87
+ count = len(to_remove)
88
+ if count > 0:
89
+ logger.debug(f"Cleaned up {count} completed task futures")
90
+
91
+ async def get_future(self, task_id: str) -> asyncio.Future:
92
+ """
93
+ Get a future for a task that will resolve when the task completes.
94
+
95
+ Args:
96
+ task_id: Task identifier
97
+
98
+ Returns:
99
+ Future that will resolve to the task result
100
+ """
101
+ async with self._futures_lock:
102
+ # Return existing future if we have one
103
+ if task_id in self._futures:
104
+ return self._futures[task_id]
105
+
106
+ # Create a new future
107
+ future = asyncio.Future()
108
+ self._futures[task_id] = future
109
+ self._pending_tasks.add(task_id)
110
+
111
+ # Ensure cleanup task is running
112
+ self._start_cleanup_task()
113
+
114
+ return future
115
+
116
+ async def set_result(self, task_id: str, result) -> None:
117
+ """
118
+ Set the result of a task future.
119
+
120
+ Args:
121
+ task_id: Task identifier
122
+ result: Result to set
123
+ """
124
+ async with self._futures_lock:
125
+ future = self._futures.get(task_id)
126
+ if future and not future.done():
127
+ future.set_result(result)
128
+ # Remove from pending tasks immediately
129
+ self._pending_tasks.discard(task_id)
130
+
131
+ async def set_exception(self, task_id: str, exception: Exception) -> None:
132
+ """
133
+ Set an exception on a task future.
134
+
135
+ Args:
136
+ task_id: Task identifier
137
+ exception: Exception to set
138
+ """
139
+ async with self._futures_lock:
140
+ future = self._futures.get(task_id)
141
+ if future and not future.done():
142
+ future.set_exception(exception)
143
+ # Remove from pending tasks immediately
144
+ self._pending_tasks.discard(task_id)
145
+
146
+ async def complete_from_result(self, task_id: str, result: any) -> None:
147
+ """
148
+ Complete a future with a result directly.
149
+
150
+ Args:
151
+ task_id: Task identifier
152
+ result: The result to set
153
+ """
154
+ await self.set_result(task_id, result)
155
+
156
+ async def complete_from_task_info(self, task_id: str, task_info: TaskInfo) -> None:
157
+ """
158
+ Complete a future based on the state of a TaskInfo object.
159
+
160
+ Args:
161
+ task_id: Task identifier
162
+ task_info: Task information
163
+ """
164
+ # First check the task state without acquiring a lock
165
+ if not task_info.is_terminal_state():
166
+ return
167
+
168
+ # Then choose the appropriate action based on state
169
+ if task_info.status == TaskStatus.COMPLETED:
170
+ await self.set_result(task_id, task_info.result)
171
+ elif task_info.status == TaskStatus.FAILED:
172
+ await self.set_exception(
173
+ task_id,
174
+ TaskExecutionError(task_info.error or "Unknown error", task_id=task_id)
175
+ )
176
+ elif task_info.status == TaskStatus.CANCELLED:
177
+ await self.set_exception(
178
+ task_id,
179
+ TaskCancellationError(task_info.error or "Task cancelled", task_id=task_id)
180
+ )
181
+
182
+ async def cancel_future(self, task_id: str) -> bool:
183
+ """
184
+ Cancel a task future.
185
+
186
+ Args:
187
+ task_id: Task identifier
188
+
189
+ Returns:
190
+ True if the future was cancelled, False if not found or already done
191
+ """
192
+ async with self._futures_lock:
193
+ future = self._futures.get(task_id)
194
+ if future and not future.done():
195
+ future.cancel()
196
+ # Remove from pending tasks immediately
197
+ self._pending_tasks.discard(task_id)
198
+ return True
199
+ return False
200
+
201
+ async def cancel_all_futures(self) -> int:
202
+ """
203
+ Cancel all pending futures.
204
+
205
+ Returns:
206
+ Number of futures cancelled
207
+ """
208
+ cancelled_count = 0
209
+ async with self._futures_lock:
210
+ # Create a list of task_ids from pending_tasks to avoid modifying during iteration
211
+ task_ids = list(self._pending_tasks)
212
+
213
+ for task_id in task_ids:
214
+ future = self._futures.get(task_id)
215
+ if future and not future.done():
216
+ future.cancel()
217
+ cancelled_count += 1
218
+
219
+ # Clear the pending tasks
220
+ self._pending_tasks.clear()
221
+
222
+ return cancelled_count
223
+
224
+ async def get_pending_count(self) -> int:
225
+ """
226
+ Get the number of pending futures.
227
+
228
+ Returns:
229
+ Number of pending futures
230
+ """
231
+ async with self._futures_lock:
232
+ return len(self._pending_tasks)