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,371 @@
1
+ """
2
+ Task Worker API Router
3
+
4
+ Factory function for creating a FastAPI router with endpoints for the AsyncTaskWorker system.
5
+ This allows for easy integration into any FastAPI application.
6
+
7
+ Example usage:
8
+ from fastapi import FastAPI
9
+ from contextlib import asynccontextmanager
10
+ from async_task_worker import AsyncTaskWorker
11
+ from async_task_worker.api import create_task_worker_router
12
+
13
+ # Create worker
14
+ worker = AsyncTaskWorker()
15
+
16
+ # Define application lifespan
17
+ @asynccontextmanager
18
+ async def lifespan(app: FastAPI):
19
+ await worker.start()
20
+ yield
21
+ await worker.stop()
22
+
23
+ # Create FastAPI app with lifespan
24
+ app = FastAPI(lifespan=lifespan)
25
+
26
+ # Create and include the router
27
+ task_router = create_task_worker_router(worker)
28
+ app.include_router(task_router)
29
+ """
30
+
31
+ import logging
32
+ from datetime import timedelta
33
+ from typing import Any, Dict, List, Optional, Tuple, Union
34
+
35
+ from fastapi import APIRouter, HTTPException, Query, status
36
+ from pydantic import BaseModel, Field, field_validator
37
+
38
+ from async_task_worker import (
39
+ AsyncTaskWorker,
40
+ TaskStatus,
41
+ get_all_task_types,
42
+ get_task_function,
43
+ TaskInfo,
44
+ )
45
+ from async_task_worker.exceptions import (
46
+ ErrorCategory,
47
+ TaskCancellationError,
48
+ TaskDefinitionError,
49
+ TaskError
50
+ )
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ # Request/Response Models
56
+ class TaskSubmitRequest(BaseModel):
57
+ """Model for task submission requests"""
58
+ task_type: str
59
+ params: Dict[str, Any] = Field(default_factory=dict)
60
+ priority: int = 0
61
+ task_id: Optional[str] = None
62
+ metadata: Optional[Dict[str, Any]] = None
63
+ timeout: Optional[float] = None # Using float for timeout (seconds)
64
+ use_cache: bool = True
65
+ cache_ttl: Optional[int] = None
66
+
67
+ @field_validator('task_type')
68
+ def validate_task_type(cls, v):
69
+ if not v:
70
+ raise ValueError("Task type cannot be empty")
71
+ return v
72
+
73
+
74
+ class TaskResponse(BaseModel):
75
+ """Model for task responses"""
76
+ id: str
77
+ status: TaskStatus
78
+ progress: float
79
+ metadata: Dict[str, Any]
80
+ result: Optional[Any] = None
81
+ error: Optional[str] = None
82
+
83
+
84
+ class TaskListResponse(BaseModel):
85
+ """Model for task list responses"""
86
+ tasks: List[TaskResponse]
87
+ count: int
88
+
89
+
90
+ class TaskTypesResponse(BaseModel):
91
+ """Model for task types list response"""
92
+ task_types: List[str]
93
+
94
+
95
+ class ApiErrorDetail(BaseModel):
96
+ """Standardized API error response detail"""
97
+ message: str
98
+ error_type: str
99
+ category: Optional[str] = None
100
+ task_id: Optional[str] = None
101
+ is_retryable: Optional[bool] = None
102
+
103
+
104
+ class HealthResponse(BaseModel):
105
+ """Model for health check response"""
106
+ status: str
107
+ worker_count: int
108
+ queue_size: int # Added queue size to health check info
109
+
110
+
111
+ def map_error_to_status_code(error: Union[Exception, TaskError]) -> Tuple[int, ApiErrorDetail]:
112
+ """
113
+ Map an error to an appropriate HTTP status code and standardized error detail.
114
+
115
+ Args:
116
+ error: The exception that occurred
117
+
118
+ Returns:
119
+ Tuple of (status_code, error_detail)
120
+ """
121
+ # Default values
122
+ status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
123
+ error_type = type(error).__name__
124
+ message = str(error)
125
+ category = None
126
+ task_id = None
127
+ is_retryable = None
128
+
129
+ # Handle TaskError types with specific mappings
130
+ if isinstance(error, TaskError):
131
+ category = error.category
132
+ task_id = error.task_id
133
+ is_retryable = error.is_retryable
134
+
135
+ # Map error categories to status codes
136
+ if error.category == ErrorCategory.VALIDATION:
137
+ status_code = status.HTTP_400_BAD_REQUEST
138
+ elif error.category == ErrorCategory.TASK_DEFINITION:
139
+ status_code = status.HTTP_400_BAD_REQUEST
140
+ elif error.category == ErrorCategory.RESOURCE:
141
+ # Check message to determine if it's a not-found error or a resources-unavailable error
142
+ if "not found" in str(error).lower():
143
+ status_code = status.HTTP_404_NOT_FOUND
144
+ else:
145
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
146
+ elif error.category == ErrorCategory.TIMEOUT:
147
+ status_code = status.HTTP_408_REQUEST_TIMEOUT
148
+ elif error.category == ErrorCategory.CANCELLATION:
149
+ status_code = status.HTTP_409_CONFLICT
150
+ # Handle common exception types
151
+ elif isinstance(error, ValueError):
152
+ status_code = status.HTTP_400_BAD_REQUEST
153
+ elif isinstance(error, TypeError):
154
+ status_code = status.HTTP_400_BAD_REQUEST
155
+ elif isinstance(error, KeyError):
156
+ status_code = status.HTTP_404_NOT_FOUND
157
+ elif isinstance(error, NotImplementedError):
158
+ status_code = status.HTTP_501_NOT_IMPLEMENTED
159
+
160
+ # Create standardized error detail
161
+ error_detail = ApiErrorDetail(
162
+ message=message,
163
+ error_type=error_type,
164
+ category=str(category) if category else None,
165
+ task_id=task_id,
166
+ is_retryable=is_retryable
167
+ )
168
+
169
+ return status_code, error_detail
170
+
171
+
172
+ def handle_task_exception(e: Exception) -> HTTPException:
173
+ """
174
+ Convert any exception to a standardized HTTPException with appropriate status code.
175
+
176
+ Args:
177
+ e: The exception to handle
178
+
179
+ Returns:
180
+ HTTPException with appropriate status code and detail
181
+ """
182
+ logger.exception(f"API error: {str(e)}")
183
+
184
+ status_code, error_detail = map_error_to_status_code(e)
185
+
186
+ # Use model_dump for Pydantic v2 compatibility
187
+ return HTTPException(
188
+ status_code=status_code,
189
+ detail=error_detail.model_dump(exclude_none=True)
190
+ )
191
+
192
+
193
+ def create_task_worker_router(
194
+ worker: AsyncTaskWorker,
195
+ prefix: str = "",
196
+ tags: Optional[List[str]] = None
197
+ ) -> APIRouter:
198
+ """
199
+ Create a FastAPI router for the AsyncTaskWorker.
200
+
201
+ Args:
202
+ worker: The AsyncTaskWorker instance to use for task management
203
+ prefix: Optional URL prefix for all routes (e.g., "/api/v1")
204
+ tags: List of tags for API documentation (defaults to ["tasks"])
205
+
206
+ Returns:
207
+ A configured FastAPI router
208
+ """
209
+ if tags is None:
210
+ tags = ["tasks"]
211
+
212
+ router = APIRouter(prefix=prefix, tags=tags)
213
+
214
+ @router.get("/types", response_model=TaskTypesResponse)
215
+ async def get_task_types_endpoint() -> TaskTypesResponse:
216
+ """Get a list of all registered task types"""
217
+ try:
218
+ task_types = await get_all_task_types()
219
+ return TaskTypesResponse(task_types=task_types)
220
+ except Exception as e:
221
+ raise handle_task_exception(e)
222
+
223
+ @router.get("/health", response_model=HealthResponse)
224
+ async def health_check() -> HealthResponse:
225
+ """Check the health of the task worker service"""
226
+ try:
227
+ # If the test fixture sets a "workers" attribute, use its length.
228
+ # Otherwise, use the worker pool's count.
229
+ worker_count = len(worker.workers) if hasattr(worker, 'workers') else worker.worker_pool.worker_count
230
+
231
+ # In a real AsyncTaskWorker, queue.qsize is a coroutine method
232
+ # But in tests it might be mocked as a property
233
+ if hasattr(worker.queue, 'qsize') and callable(worker.queue.qsize):
234
+ queue_size = await worker.queue.qsize()
235
+ else:
236
+ # For tests where it might be a property
237
+ queue_size = worker.queue.qsize
238
+
239
+ return HealthResponse(
240
+ status="ok" if worker.running else "stopped",
241
+ worker_count=worker_count,
242
+ queue_size=queue_size,
243
+ )
244
+ except Exception as e:
245
+ # Health check errors are generally server-side issues
246
+ raise handle_task_exception(e)
247
+
248
+ @router.post("/tasks", response_model=TaskResponse, status_code=status.HTTP_201_CREATED)
249
+ async def create_task(request: TaskSubmitRequest) -> TaskResponse:
250
+ """Submit a new task for processing"""
251
+ try:
252
+ # Get the task function
253
+ task_func = await get_task_function(request.task_type)
254
+ if task_func is None:
255
+ # Use TaskDefinitionError for consistency with error handling
256
+ raise TaskDefinitionError(f"Unknown task type: {request.task_type}")
257
+
258
+ # Add metadata about the task type
259
+ metadata = request.metadata or {}
260
+ metadata["task_type"] = request.task_type
261
+
262
+ # Submit the task with new parameters
263
+ task_id = await worker.add_task(
264
+ task_func,
265
+ **request.params,
266
+ priority=request.priority,
267
+ task_id=request.task_id,
268
+ metadata=metadata,
269
+ timeout=request.timeout,
270
+ use_cache=request.use_cache,
271
+ cache_ttl=request.cache_ttl,
272
+ )
273
+
274
+ # Get task info (asynchronously)
275
+ task_info = await worker.get_task_info(task_id)
276
+ if task_info is None:
277
+ # Internal error if task was created but info not found
278
+ raise TaskError(
279
+ message=f"Task {task_id} created but info not found",
280
+ category=ErrorCategory.INTERNAL
281
+ )
282
+
283
+ return TaskResponse(
284
+ id=task_info.id,
285
+ status=task_info.status,
286
+ progress=task_info.progress,
287
+ metadata=task_info.metadata,
288
+ result=task_info.result,
289
+ error=task_info.error,
290
+ )
291
+ except Exception as e:
292
+ # Use standardized error handling
293
+ raise handle_task_exception(e)
294
+
295
+ @router.get("/tasks/{task_id}", response_model=TaskResponse)
296
+ async def get_task(task_id: str) -> TaskResponse:
297
+ """Get information about a specific task by ID"""
298
+ try:
299
+ task_info = await worker.get_task_info(task_id)
300
+ if task_info is None:
301
+ raise TaskError(
302
+ message=f"Task {task_id} not found",
303
+ category=ErrorCategory.RESOURCE,
304
+ task_id=task_id
305
+ )
306
+
307
+ return TaskResponse(
308
+ id=task_info.id,
309
+ status=task_info.status,
310
+ progress=task_info.progress,
311
+ metadata=task_info.metadata,
312
+ result=task_info.result,
313
+ error=task_info.error,
314
+ )
315
+ except Exception as e:
316
+ raise handle_task_exception(e)
317
+
318
+ @router.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
319
+ async def cancel_task(task_id: str) -> None:
320
+ """Cancel a running or pending task"""
321
+ try:
322
+ task_info = await worker.get_task_info(task_id)
323
+ if task_info is None:
324
+ raise TaskError(
325
+ message=f"Task {task_id} not found",
326
+ category=ErrorCategory.RESOURCE,
327
+ task_id=task_id
328
+ )
329
+
330
+ if task_info.status in [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED]:
331
+ # Task already finished, just return success
332
+ return
333
+
334
+ cancelled = await worker.cancel_task(task_id)
335
+ if not cancelled:
336
+ raise TaskCancellationError(
337
+ message=f"Task {task_id} could not be cancelled",
338
+ task_id=task_id
339
+ )
340
+ except Exception as e:
341
+ raise handle_task_exception(e)
342
+
343
+ @router.get("/tasks", response_model=TaskListResponse)
344
+ async def list_tasks(
345
+ task_status: Optional[TaskStatus] = None,
346
+ limit: int = Query(50, ge=1, le=100),
347
+ older_than_minutes: Optional[int] = Query(None, ge=0),
348
+ ) -> TaskListResponse:
349
+ """List tasks with optional filtering"""
350
+ try:
351
+ older_than = timedelta(minutes=older_than_minutes) if older_than_minutes else None
352
+ tasks: List[TaskInfo] = await worker.get_all_tasks(status=task_status, limit=limit, older_than=older_than)
353
+
354
+ return TaskListResponse(
355
+ tasks=[
356
+ TaskResponse(
357
+ id=task.id,
358
+ status=task.status,
359
+ progress=task.progress,
360
+ metadata=task.metadata,
361
+ result=task.result,
362
+ error=task.error,
363
+ )
364
+ for task in tasks
365
+ ],
366
+ count=len(tasks),
367
+ )
368
+ except Exception as e:
369
+ raise handle_task_exception(e)
370
+
371
+ return router