Initial commit: Test GLM project
This commit is contained in:
@@ -0,0 +1,437 @@
|
||||
# Subtask: Task Producer API
|
||||
|
||||
**Parent Task**: Decomp/003
|
||||
**Subtask ID**: Decomp/003-02
|
||||
**Dependencies**: Decomp-003-01 (Database Schema)
|
||||
|
||||
## Description
|
||||
|
||||
Implement task producer API for enqueueing tasks. Support both synchronous (execute now) and asynchronous (enqueue for later) execution. Handle task scheduling with priorities, delays, and cron expressions.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Enqueue tasks for async execution
|
||||
- Execute tasks synchronously and return result
|
||||
- Schedule tasks for future execution
|
||||
- Set task priorities
|
||||
- Support task chaining (one task's result feeds into next)
|
||||
- Support task groups (parallel execution)
|
||||
- Task deduplication prevention
|
||||
- Task cancellation
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**Task producer client**:
|
||||
```python
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional, List, Union, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
import asyncio
|
||||
|
||||
class TaskPriority(Enum):
|
||||
HIGH = 0
|
||||
ABOVE_NORMAL = 3
|
||||
NORMAL = 5
|
||||
BELOW_NORMAL = 7
|
||||
LOW = 10
|
||||
|
||||
class TaskStatus(Enum):
|
||||
PENDING = "pending"
|
||||
RUNNING = "running"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled"
|
||||
RETRY = "retry"
|
||||
|
||||
@dataclass
|
||||
class TaskResult:
|
||||
"""Result of a task execution."""
|
||||
task_id: str
|
||||
status: TaskStatus
|
||||
result: Any = None
|
||||
error: Optional[str] = None
|
||||
traceback: Optional[str] = None
|
||||
started_at: Optional[datetime] = None
|
||||
completed_at: Optional[datetime] = None
|
||||
|
||||
class TaskProducer:
|
||||
"""Client for enqueueing and managing tasks."""
|
||||
|
||||
def __init__(self, broker, default_queue: str = "default"):
|
||||
self.broker = broker # Redis or database connection
|
||||
self.default_queue = default_queue
|
||||
|
||||
async def apply_async(
|
||||
self,
|
||||
task_func: Union[str, Callable],
|
||||
args: List[Any] = None,
|
||||
kwargs: dict = None,
|
||||
queue: str = None,
|
||||
priority: TaskPriority = TaskPriority.NORMAL,
|
||||
eta: Optional[datetime] = None,
|
||||
expires: Optional[datetime] = None,
|
||||
retry: bool = True,
|
||||
max_retries: int = 3,
|
||||
task_id: str = None,
|
||||
group_id: str = None,
|
||||
dependencies: List[str] = None
|
||||
) -> str:
|
||||
"""
|
||||
Apply a task asynchronously.
|
||||
|
||||
Args:
|
||||
task_func: Function name or callable
|
||||
args: Positional arguments
|
||||
kwargs: Keyword arguments
|
||||
queue: Queue name (default: self.default_queue)
|
||||
priority: Task priority
|
||||
eta: Earliest time to execute
|
||||
expires: Task expiration time
|
||||
retry: Enable retry on failure
|
||||
max_retries: Maximum retry attempts
|
||||
task_id: Custom task ID (auto-generated if None)
|
||||
group_id: Task group ID for grouped tasks
|
||||
dependencies: List of task IDs this task depends on
|
||||
|
||||
Returns:
|
||||
Task ID
|
||||
"""
|
||||
# Get task name
|
||||
if callable(task_func):
|
||||
task_name = f"{task_func.__module__}.{task_func.__name__}"
|
||||
else:
|
||||
task_name = task_func
|
||||
|
||||
# Generate task ID if not provided
|
||||
task_id = task_id or str(uuid.uuid4())
|
||||
|
||||
# Serialize arguments
|
||||
args_data = self._serialize_args(args or [])
|
||||
kwargs_data = self._serialize_args(kwargs or {})
|
||||
|
||||
# Build task data
|
||||
task_data = {
|
||||
"id": task_id,
|
||||
"name": task_name,
|
||||
"args": args_data,
|
||||
"kwargs": kwargs_data,
|
||||
"queue": queue or self.default_queue,
|
||||
"priority": priority.value,
|
||||
"retry": retry,
|
||||
"max_retries": max_retries,
|
||||
"retry_count": 0,
|
||||
"group_id": group_id,
|
||||
"created_at": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
# Add to database
|
||||
await self._persist_task(
|
||||
task_data=task_data,
|
||||
eta=eta,
|
||||
expires=expires,
|
||||
dependencies=dependencies
|
||||
)
|
||||
|
||||
# Add to broker queue (unless scheduled for future)
|
||||
if eta is None or eta <= datetime.now(timezone.utc):
|
||||
await self.broker.enqueue(
|
||||
queue=queue or self.default_queue,
|
||||
task_id=task_id,
|
||||
priority=priority.value
|
||||
)
|
||||
else:
|
||||
# Schedule for later
|
||||
await self.broker.schedule(
|
||||
task_id=task_id,
|
||||
scheduled_time=eta
|
||||
)
|
||||
|
||||
return task_id
|
||||
|
||||
async def apply(
|
||||
self,
|
||||
task_func: Union[str, Callable],
|
||||
args: List[Any] = None,
|
||||
kwargs: dict = None,
|
||||
timeout: Optional[float] = None
|
||||
) -> TaskResult:
|
||||
"""
|
||||
Apply a task synchronously and wait for result.
|
||||
|
||||
Executes the task inline (not through worker).
|
||||
"""
|
||||
# Get task name
|
||||
if callable(task_func):
|
||||
task_name = f"{task_func.__module__}.{task_func.__name__}"
|
||||
func = task_func
|
||||
else:
|
||||
task_name = task_func
|
||||
func = self._get_task_function(task_name)
|
||||
|
||||
# Execute
|
||||
start_time = datetime.now(timezone.utc)
|
||||
try:
|
||||
if asyncio.iscoroutinefunction(func):
|
||||
result = await asyncio.wait_for(
|
||||
func(*(args or []), **(kwargs or {})),
|
||||
timeout=timeout
|
||||
)
|
||||
else:
|
||||
result = await asyncio.to_thread(
|
||||
func, *(args or []), **(kwargs or {})
|
||||
)
|
||||
|
||||
return TaskResult(
|
||||
task_id=str(uuid.uuid4()),
|
||||
status=TaskStatus.COMPLETED,
|
||||
result=result,
|
||||
started_at=start_time,
|
||||
completed_at=datetime.now(timezone.utc)
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return TaskResult(
|
||||
task_id=str(uuid.uuid4()),
|
||||
status=TaskStatus.FAILED,
|
||||
error="Task timed out",
|
||||
started_at=start_time,
|
||||
completed_at=datetime.now(timezone.utc)
|
||||
)
|
||||
except Exception as e:
|
||||
return TaskResult(
|
||||
task_id=str(uuid.uuid4()),
|
||||
status=TaskStatus.FAILED,
|
||||
error=str(e),
|
||||
traceback=traceback.format_exc(),
|
||||
started_at=start_time,
|
||||
completed_at=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
async def chain(self, *tasks) -> str:
|
||||
"""
|
||||
Chain tasks: each task receives the previous task's result.
|
||||
|
||||
Returns:
|
||||
Chain ID (last task's ID)
|
||||
"""
|
||||
parent_id = None
|
||||
|
||||
for task in tasks:
|
||||
if parent_id:
|
||||
# Set dependency on previous task
|
||||
task["dependencies"] = task.get("dependencies", []) + [parent_id]
|
||||
parent_id = await self.apply_async(**task)
|
||||
|
||||
return parent_id
|
||||
|
||||
async def group(self, *tasks) -> str:
|
||||
"""
|
||||
Group tasks: execute in parallel.
|
||||
|
||||
Returns:
|
||||
Group ID
|
||||
"""
|
||||
group_id = str(uuid.uuid4())
|
||||
|
||||
# Enqueue all tasks with same group_id
|
||||
task_ids = []
|
||||
for task in tasks:
|
||||
task["group_id"] = group_id
|
||||
task_id = await self.apply_async(**task)
|
||||
task_ids.append(task_id)
|
||||
|
||||
return group_id
|
||||
|
||||
async def chord(self, header, body) -> str:
|
||||
"""
|
||||
Chord: execute tasks in parallel, then callback with results.
|
||||
|
||||
Args:
|
||||
header: List of tasks to execute in parallel
|
||||
body: Callback task (receives list of results)
|
||||
|
||||
Returns:
|
||||
Chord ID
|
||||
"""
|
||||
group_id = await self.group(*header)
|
||||
|
||||
# Create a barrier task that waits for group completion
|
||||
# then executes the callback
|
||||
barrier_task = {
|
||||
"task_func": "_chord_barrier",
|
||||
"kwargs": {
|
||||
"group_id": group_id,
|
||||
"callback": body
|
||||
}
|
||||
}
|
||||
|
||||
return await self.apply_async(**barrier_task)
|
||||
|
||||
async def cancel(self, task_id: str) -> bool:
|
||||
"""Cancel a pending or running task."""
|
||||
# Update database
|
||||
async with self.broker.db.acquire() as conn:
|
||||
result = await conn.execute(
|
||||
"""UPDATE tasks
|
||||
SET status = 'cancelled', completed_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'running')""",
|
||||
task_id
|
||||
)
|
||||
return result != "UPDATE 0"
|
||||
|
||||
async def get_result(self, task_id: str, timeout: Optional[float] = None) -> TaskResult:
|
||||
"""Get task result, waiting if not ready."""
|
||||
start_time = datetime.now(timezone.utc)
|
||||
|
||||
while True:
|
||||
result = await self._get_task_result(task_id)
|
||||
if result.status in (TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED):
|
||||
return result
|
||||
|
||||
if timeout and (datetime.now(timezone.utc) - start_time).total_seconds() > timeout:
|
||||
raise TimeoutError(f"Task {task_id} did not complete within {timeout}s")
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
async def _persist_task(
|
||||
self,
|
||||
task_data: dict,
|
||||
eta: Optional[datetime],
|
||||
expires: Optional[datetime],
|
||||
dependencies: List[str]
|
||||
):
|
||||
"""Persist task to database."""
|
||||
async with self.broker.db.acquire() as conn:
|
||||
# Get queue ID
|
||||
queue_id = await conn.fetchval(
|
||||
"SELECT id FROM task_queues WHERE name = $1",
|
||||
task_data["queue"]
|
||||
)
|
||||
|
||||
# Insert task
|
||||
task_id = await conn.fetchval(
|
||||
"""INSERT INTO tasks
|
||||
(id, queue_id, task_name, args, kwargs, priority,
|
||||
scheduled_at, expires_at, max_retries, task_group_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING id""",
|
||||
task_data["id"],
|
||||
queue_id,
|
||||
task_data["name"],
|
||||
json.dumps(task_data["args"]),
|
||||
json.dumps(task_data["kwargs"]),
|
||||
task_data["priority"],
|
||||
eta,
|
||||
expires,
|
||||
task_data["max_retries"],
|
||||
task_data["group_id"]
|
||||
)
|
||||
|
||||
# Insert dependencies
|
||||
if dependencies:
|
||||
for dep_id in dependencies:
|
||||
await conn.execute(
|
||||
"INSERT INTO task_dependencies (task_id, depends_on_task_id) VALUES ($1, $2)",
|
||||
task_id, dep_id
|
||||
)
|
||||
|
||||
def _serialize_args(self, args: Any) -> str:
|
||||
"""Serialize arguments to JSON."""
|
||||
return json.dumps(args, default=str)
|
||||
|
||||
async def _get_task_result(self, task_id: str) -> TaskResult:
|
||||
"""Get task result from database."""
|
||||
async with self.broker.db.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT * FROM tasks WHERE id = $1",
|
||||
task_id
|
||||
)
|
||||
|
||||
if not row:
|
||||
raise ValueError(f"Task {task_id} not found")
|
||||
|
||||
return TaskResult(
|
||||
task_id=task_id,
|
||||
status=TaskStatus(row["status"]),
|
||||
result=row["result"],
|
||||
error=row["error"],
|
||||
traceback=row["traceback"],
|
||||
started_at=row["started_at"],
|
||||
completed_at=row["completed_at"]
|
||||
)
|
||||
```
|
||||
|
||||
**Decorator for task functions**:
|
||||
```python
|
||||
def task(
|
||||
name: str = None,
|
||||
queue: str = "default",
|
||||
priority: TaskPriority = TaskPriority.NORMAL,
|
||||
max_retries: int = 3,
|
||||
retry_backoff: bool = True
|
||||
):
|
||||
"""
|
||||
Decorator to mark a function as a task.
|
||||
|
||||
Usage:
|
||||
@task(name="send_email", queue="notifications")
|
||||
def send_email(to: str, subject: str, body: str):
|
||||
...
|
||||
"""
|
||||
def decorator(func):
|
||||
# Register task function
|
||||
TASK_REGISTRY[name or f"{func.__module__}.{func.__name__}"] = {
|
||||
"func": func,
|
||||
"queue": queue,
|
||||
"priority": priority,
|
||||
"max_retries": max_retries,
|
||||
"retry_backoff": retry_backoff
|
||||
}
|
||||
|
||||
# Add apply_async method to function
|
||||
def apply_async(*args, **kwargs):
|
||||
producer = get_current_producer()
|
||||
return producer.apply_async(
|
||||
task_func=func,
|
||||
args=args,
|
||||
kwargs=kwargs,
|
||||
queue=queue,
|
||||
priority=priority
|
||||
)
|
||||
|
||||
func.apply_async = apply_async
|
||||
func.delay = lambda *a, **k: producer.apply_async(func, a, k)
|
||||
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
# Global task registry
|
||||
TASK_REGISTRY = {}
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Tasks can be enqueued for async execution
|
||||
- [ ] Synchronous execution returns result directly
|
||||
- [ ] Task priorities are respected
|
||||
- [ ] Task chains execute sequentially
|
||||
- [ ] Task groups execute in parallel
|
||||
- [ ] Scheduled tasks execute at specified time
|
||||
- [ ] Tasks can be cancelled
|
||||
|
||||
## Notes
|
||||
|
||||
**Trade-offs**:
|
||||
- In-memory vs persistent task storage: Persistent for durability
|
||||
- Direct function reference vs string name: Both supported
|
||||
|
||||
**Performance**:
|
||||
- Use connection pooling for database operations
|
||||
- Batch enqueue operations for efficiency
|
||||
|
||||
**Alternatives considered**:
|
||||
- Celery-compatible API: Rejected, too complex
|
||||
- Pure async API: Sync wrapper provided for convenience
|
||||
Reference in New Issue
Block a user