async-task-worker 0.1.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_task_worker-0.1.0.dist-info/METADATA +872 -0
- async_task_worker-0.1.0.dist-info/RECORD +9 -0
- async_task_worker-0.1.0.dist-info/WHEEL +4 -0
- async_task_worker-0.1.0.dist-info/licenses/LICENSE +21 -0
- src/async_task_worker/__init__.py +38 -0
- src/async_task_worker/task_cache.py +262 -0
- src/async_task_worker/task_registry.py +83 -0
- src/async_task_worker/task_worker.py +633 -0
- src/async_task_worker/task_worker_api.py +248 -0
|
@@ -0,0 +1,248 @@
|
|
|
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.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
|
|
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
|
+
)
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# Request/Response Models
|
|
49
|
+
class TaskSubmitRequest(BaseModel):
|
|
50
|
+
"""Model for task submission requests"""
|
|
51
|
+
task_type: str
|
|
52
|
+
params: Dict[str, Any] = Field(default_factory=dict)
|
|
53
|
+
priority: int = 0
|
|
54
|
+
task_id: Optional[str] = None
|
|
55
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
56
|
+
timeout: Optional[int] = None
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
@field_validator('task_type')
|
|
60
|
+
def validate_task_type(cls, v):
|
|
61
|
+
"""Validate task type is registered"""
|
|
62
|
+
if get_task_function(v) is None:
|
|
63
|
+
raise ValueError(f"Task type '{v}' is not registered")
|
|
64
|
+
return v
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class TaskResponse(BaseModel):
|
|
68
|
+
"""Model for task responses"""
|
|
69
|
+
id: str
|
|
70
|
+
status: TaskStatus
|
|
71
|
+
progress: float
|
|
72
|
+
metadata: Dict[str, Any]
|
|
73
|
+
result: Optional[Any] = None
|
|
74
|
+
error: Optional[str] = None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class TaskListResponse(BaseModel):
|
|
78
|
+
"""Model for task list responses"""
|
|
79
|
+
tasks: List[TaskResponse]
|
|
80
|
+
count: int
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class TaskTypesResponse(BaseModel):
|
|
84
|
+
"""Model for task types list response"""
|
|
85
|
+
task_types: List[str]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class HealthResponse(BaseModel):
|
|
89
|
+
"""Model for health check response"""
|
|
90
|
+
status: str
|
|
91
|
+
worker_count: int
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def create_task_worker_router(
|
|
95
|
+
worker: AsyncTaskWorker,
|
|
96
|
+
prefix: str = "",
|
|
97
|
+
tags: Optional[List[str]] = None
|
|
98
|
+
) -> APIRouter:
|
|
99
|
+
"""
|
|
100
|
+
Create a FastAPI router for the AsyncTaskWorker.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
worker: The AsyncTaskWorker instance to use for task management
|
|
104
|
+
prefix: Optional URL prefix for all routes (e.g., "/api/v1")
|
|
105
|
+
tags: List of tags for API documentation (defaults to ["tasks"])
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
A configured FastAPI router
|
|
109
|
+
"""
|
|
110
|
+
if tags is None:
|
|
111
|
+
tags = ["tasks"]
|
|
112
|
+
|
|
113
|
+
router = APIRouter(prefix=prefix, tags=tags)
|
|
114
|
+
|
|
115
|
+
# First define endpoints that could conflict with parameterized routes
|
|
116
|
+
# Define the task types endpoint first to avoid path conflicts
|
|
117
|
+
@router.get("/types", response_model=TaskTypesResponse)
|
|
118
|
+
async def get_task_types() -> TaskTypesResponse:
|
|
119
|
+
"""Get a list of all registered task types"""
|
|
120
|
+
task_types = get_all_task_types()
|
|
121
|
+
return TaskTypesResponse(task_types=task_types)
|
|
122
|
+
|
|
123
|
+
# Health check endpoint
|
|
124
|
+
@router.get("/health", response_model=HealthResponse)
|
|
125
|
+
async def health_check() -> HealthResponse:
|
|
126
|
+
"""Check the health of the task worker service"""
|
|
127
|
+
return HealthResponse(
|
|
128
|
+
status="ok" if worker.running else "stopped",
|
|
129
|
+
worker_count=len(worker.workers),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Now define the tasks endpoints
|
|
133
|
+
@router.post("/tasks", response_model=TaskResponse, status_code=status.HTTP_201_CREATED)
|
|
134
|
+
async def create_task(request: TaskSubmitRequest) -> TaskResponse:
|
|
135
|
+
"""Submit a new task for processing"""
|
|
136
|
+
task_func = get_task_function(request.task_type)
|
|
137
|
+
if task_func is None:
|
|
138
|
+
raise HTTPException(
|
|
139
|
+
status_code=status.HTTP_400_BAD_REQUEST,
|
|
140
|
+
detail=f"Unknown task type: {request.task_type}",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# Add metadata about the task type
|
|
144
|
+
metadata = request.metadata or {}
|
|
145
|
+
metadata["task_type"] = request.task_type
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
# Submit the task
|
|
149
|
+
task_id = await worker.add_task(
|
|
150
|
+
task_func,
|
|
151
|
+
**request.params,
|
|
152
|
+
priority=request.priority,
|
|
153
|
+
task_id=request.task_id,
|
|
154
|
+
metadata=metadata,
|
|
155
|
+
timeout=request.timeout,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# Get task info
|
|
159
|
+
task_info = worker.get_task_info(task_id)
|
|
160
|
+
if task_info is None:
|
|
161
|
+
raise HTTPException(
|
|
162
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
163
|
+
detail="Task created but info not found",
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
return TaskResponse(
|
|
167
|
+
id=task_info.id,
|
|
168
|
+
status=task_info.status,
|
|
169
|
+
progress=task_info.progress,
|
|
170
|
+
metadata=task_info.metadata,
|
|
171
|
+
result=task_info.result,
|
|
172
|
+
error=task_info.error,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
except Exception as e:
|
|
176
|
+
logger.exception(f"Error submitting task: {str(e)}")
|
|
177
|
+
raise HTTPException(
|
|
178
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
179
|
+
detail=f"Failed to submit task: {str(e)}",
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
@router.get("/tasks/{task_id}", response_model=TaskResponse)
|
|
183
|
+
async def get_task(task_id: str) -> TaskResponse:
|
|
184
|
+
"""Get information about a specific task by ID"""
|
|
185
|
+
task_info = worker.get_task_info(task_id)
|
|
186
|
+
if task_info is None:
|
|
187
|
+
raise HTTPException(
|
|
188
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
189
|
+
detail=f"Task {task_id} not found",
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
return TaskResponse(
|
|
193
|
+
id=task_info.id,
|
|
194
|
+
status=task_info.status,
|
|
195
|
+
progress=task_info.progress,
|
|
196
|
+
metadata=task_info.metadata,
|
|
197
|
+
result=task_info.result,
|
|
198
|
+
error=task_info.error,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
@router.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
202
|
+
async def cancel_task(task_id: str) -> None:
|
|
203
|
+
"""Cancel a running or pending task"""
|
|
204
|
+
task_info = worker.get_task_info(task_id)
|
|
205
|
+
if task_info is None:
|
|
206
|
+
raise HTTPException(
|
|
207
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
208
|
+
detail=f"Task {task_id} not found",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
if task_info.status in [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED]:
|
|
212
|
+
# Task already finished, just return success
|
|
213
|
+
return
|
|
214
|
+
|
|
215
|
+
cancelled = await worker.cancel_task(task_id)
|
|
216
|
+
if not cancelled:
|
|
217
|
+
raise HTTPException(
|
|
218
|
+
status_code=status.HTTP_409_CONFLICT,
|
|
219
|
+
detail=f"Task {task_id} could not be cancelled",
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
@router.get("/tasks", response_model=TaskListResponse)
|
|
223
|
+
async def list_tasks(
|
|
224
|
+
task_status: Optional[TaskStatus] = None,
|
|
225
|
+
limit: int = Query(50, ge=1, le=100),
|
|
226
|
+
older_than_minutes: Optional[int] = Query(None, ge=0),
|
|
227
|
+
) -> TaskListResponse:
|
|
228
|
+
"""List tasks with optional filtering"""
|
|
229
|
+
older_than = timedelta(minutes=older_than_minutes) if older_than_minutes else None
|
|
230
|
+
|
|
231
|
+
tasks = worker.get_all_tasks(status=task_status, limit=limit, older_than=older_than)
|
|
232
|
+
|
|
233
|
+
return TaskListResponse(
|
|
234
|
+
tasks=[
|
|
235
|
+
TaskResponse(
|
|
236
|
+
id=task.id,
|
|
237
|
+
status=task.status,
|
|
238
|
+
progress=task.progress,
|
|
239
|
+
metadata=task.metadata,
|
|
240
|
+
result=task.result,
|
|
241
|
+
error=task.error,
|
|
242
|
+
)
|
|
243
|
+
for task in tasks
|
|
244
|
+
],
|
|
245
|
+
count=len(tasks),
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
return router
|