16 KiB
16 KiB
Subtask: Task Worker Implementation
Parent Task: Decomp/003 Subtask ID: Decomp/003-03 Dependencies: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API)
Description
Implement task worker that polls queues, executes tasks, and reports results. Worker must support concurrent task execution, graceful shutdown, and auto-recovery from failures.
Requirements
- Poll task queues for pending tasks
- Execute task functions with provided arguments
- Support concurrent task execution (configurable concurrency)
- Report task results (success/failure) to database
- Send heartbeats to indicate worker liveness
- Handle graceful shutdown (complete running tasks before exit)
- Auto-reconnection to broker after connection loss
- Support multiple queues per worker
- Task timeout enforcement
- Worker registration on startup
Technical Specifications
Worker core implementation:
import asyncio
import signal
import uuid
import os
import traceback
from typing import Set, Optional, List, Dict, Any
from datetime import datetime, timezone
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
@dataclass
class WorkerConfig:
"""Worker configuration."""
worker_name: Optional[str] = None # Auto-generated if None
queues: List[str] = None # Default: ["default"]
concurrency: int = 1 # Max concurrent tasks
prefetched_tasks: int = 2 # Tasks to prefetch
heartbeat_interval: float = 5.0 # Seconds
task_timeout: Optional[float] = None # Default task timeout
max_tasks_per_child: Optional[int] = None # Restart after N tasks
broker_url: str = "redis://localhost:6379"
db_url: str = "postgresql://localhost/tasks"
class TaskWorker:
"""Task execution worker."""
def __init__(self, config: WorkerConfig):
self.config = config
self.worker_name = config.worker_name or f"worker-{os.getpid()}-{uuid.uuid4().hex[:8]}"
self.queues = config.queues or ["default"]
self.concurrency = config.concurrency
self.running_tasks: Set[str] = set()
self.should_stop = False
self.task_count = 0
# Connections
self.broker = None
self.db = None
self.worker_id = None
# Semaphore for concurrency control
self.semaphore = asyncio.Semaphore(self.concurrency)
# Background tasks
self.heartbeat_task = None
self.scheduler_task = None
async def start(self):
"""Start the worker."""
logger.info(f"Starting worker: {self.worker_name}")
# Initialize connections
await self._connect()
# Register worker
self.worker_id = await self._register_worker()
logger.info(f"Worker registered with ID: {self.worker_id}")
# Start heartbeat task
self.heartbeat_task = asyncio.create_task(self._heartbeat_loop())
# Start scheduled task checker
self.scheduler_task = asyncio.create_task(self._scheduled_task_loop())
# Setup signal handlers
self._setup_signals()
# Main worker loop
await self._main_loop()
async def _connect(self):
"""Initialize broker and database connections."""
from .broker import RedisBroker
from .database import DatabaseConnection
self.broker = RedisBroker(url=self.config.broker_url)
await self.broker.connect()
self.db = DatabaseConnection(url=self.config.db_url)
await self.db.connect()
async def _register_worker(self) -> int:
"""Register worker in database."""
async with self.db.acquire() as conn:
worker_id = await conn.fetchval(
"""INSERT INTO workers (worker_name, hostname, pid, queues, concurrency)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (worker_name) DO UPDATE
SET last_heartbeat = NOW(), current_tasks = 0
RETURNING id""",
self.worker_name,
os.uname().nodename,
os.getpid(),
self.queues,
self.concurrency
)
return worker_id
async def _heartbeat_loop(self):
"""Send periodic heartbeats."""
while not self.should_stop:
try:
await self._send_heartbeat()
await asyncio.sleep(self.config.heartbeat_interval)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Heartbeat error: {e}")
await asyncio.sleep(self.config.heartbeat_interval)
async def _send_heartbeat(self):
"""Send heartbeat to database."""
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE workers
SET last_heartbeat = NOW(), current_tasks = $1
WHERE id = $2""",
len(self.running_tasks),
self.worker_id
)
async def _scheduled_task_loop(self):
"""Check for scheduled tasks ready to execute."""
while not self.should_stop:
try:
await self._check_scheduled_tasks()
await asyncio.sleep(10) # Check every 10 seconds
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Scheduled task check error: {e}")
await asyncio.sleep(10)
async def _check_scheduled_tasks(self):
"""Move scheduled tasks to pending queue."""
async with self.db.acquire() as conn:
# Find tasks whose scheduled time has passed
rows = await conn.fetch(
"""UPDATE tasks
SET status = 'pending'
WHERE status = 'pending'
AND scheduled_at <= NOW()
AND scheduled_at IS NOT NULL
RETURNING id, queue_id"""
)
for row in rows:
task_id = row["id"]
queue_id = row["queue_id"]
# Get queue name
queue_name = await conn.fetchval(
"SELECT name FROM task_queues WHERE id = $1",
queue_id
)
# Add to broker queue
await self.broker.enqueue(queue_name, task_id)
async def _main_loop(self):
"""Main worker loop - fetch and execute tasks."""
while not self.should_stop:
try:
# Check if we should restart (max tasks per child)
if (self.config.max_tasks_per_child and
self.task_count >= self.config.max_tasks_per_child):
logger.info(f"Reached max_tasks_per_child ({self.task_count}), restarting...")
await self._graceful_shutdown()
return
# Try to fetch a task from any queue
task = await self._fetch_task()
if task:
# Execute task in semaphore-controlled coroutine
asyncio.create_task(self._execute_task_wrapper(task))
else:
# No tasks available, wait a bit
await asyncio.sleep(0.5)
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in main loop: {e}", exc_info=True)
await asyncio.sleep(1)
async def _fetch_task(self) -> Optional[dict]:
"""Fetch a task from the queue."""
for queue_name in self.queues:
# Get queue ID
async with self.db.acquire() as conn:
queue_id = await conn.fetchval(
"SELECT id FROM task_queues WHERE name = $1",
queue_name
)
if not queue_id:
logger.warning(f"Queue not found: {queue_name}")
continue
# Try to dequeue from broker
task_id = await self.broker.dequeue(queue_name)
if task_id:
# Fetch full task data from database
async with self.db.acquire() as conn:
task = await conn.fetchrow(
"""SELECT * FROM tasks WHERE id = $1""",
task_id
)
if task:
return dict(task)
return None
async def _execute_task_wrapper(self, task: dict):
"""Wrapper to execute task with semaphore control."""
async with self.semaphore:
task_id = task["id"]
self.running_tasks.add(task_id)
try:
await self._execute_task(task)
except Exception as e:
logger.error(f"Error executing task {task_id}: {e}")
# Mark as failed
await self._mark_task_failed(task_id, str(e), traceback.format_exc())
finally:
self.running_tasks.discard(task_id)
self.task_count += 1
async def _execute_task(self, task: dict):
"""Execute a single task."""
task_id = task["id"]
task_name = task["task_name"]
args = self._deserialize_args(task["args"])
kwargs = self._deserialize_args(task["kwargs"])
logger.info(f"Executing task {task_id}: {task_name}")
# Mark as running
await self._mark_task_running(task_id)
# Get task function
from .producer import TASK_REGISTRY
task_info = TASK_REGISTRY.get(task_name)
if not task_info:
raise ValueError(f"Task function not registered: {task_name}")
func = task_info["func"]
# Execute with timeout
timeout = self.config.task_timeout
try:
if asyncio.iscoroutinefunction(func):
if timeout:
result = await asyncio.wait_for(
func(*args, **kwargs),
timeout=timeout
)
else:
result = await func(*args, **kwargs)
else:
if timeout:
result = await asyncio.wait_for(
asyncio.to_thread(func, *args, **kwargs),
timeout=timeout
)
else:
result = await asyncio.to_thread(func, *args, **kwargs)
# Mark as completed
await self._mark_task_completed(task_id, result)
logger.info(f"Task {task_id} completed successfully")
except asyncio.TimeoutError:
error_msg = f"Task timed out after {timeout}s"
await self._mark_task_failed(task_id, error_msg, None)
logger.warning(f"Task {task_id} timed out")
except Exception as e:
await self._mark_task_failed(task_id, str(e), traceback.format_exc())
logger.error(f"Task {task_id} failed: {e}")
async def _mark_task_running(self, task_id: str):
"""Mark task as running."""
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE tasks
SET status = 'running', started_at = NOW(), worker_id = $1
WHERE id = $2""",
self.worker_id,
task_id
)
async def _mark_task_completed(self, task_id: str, result: Any):
"""Mark task as completed with result."""
from .producer import TaskProducer
result_json = TaskProducer._serialize_args(None, result)
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE tasks
SET status = 'completed',
result = $1,
completed_at = NOW(),
current_tasks = current_tasks - 1
WHERE id = $2""",
result_json,
task_id
)
# Decrement worker task count
await conn.execute(
"UPDATE workers SET current_tasks = current_tasks - 1 WHERE id = $1",
self.worker_id
)
async def _mark_task_failed(self, task_id: str, error: str, tb: Optional[str]):
"""Mark task as failed."""
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE tasks
SET status = 'failed',
error = $1,
traceback = $2,
completed_at = NOW()
WHERE id = $3""",
error,
tb,
task_id
)
# Decrement worker task count
await conn.execute(
"UPDATE workers SET current_tasks = current_tasks - 1 WHERE id = $1",
self.worker_id
)
def _deserialize_args(self, args_json: str) -> Any:
"""Deserialize arguments from JSON."""
import json
return json.loads(args_json)
def _setup_signals(self):
"""Setup signal handlers for graceful shutdown."""
def signal_handler(sig, frame):
logger.info(f"Received signal {sig}, initiating graceful shutdown...")
asyncio.create_task(self._graceful_shutdown())
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
async def _graceful_shutdown(self):
"""Gracefully shutdown the worker."""
if self.should_stop:
return
logger.info("Initiating graceful shutdown...")
self.should_stop = True
# Wait for running tasks to complete
if self.running_tasks:
logger.info(f"Waiting for {len(self.running_tasks)} running tasks...")
while self.running_tasks:
await asyncio.sleep(0.5)
# Cancel background tasks
if self.heartbeat_task:
self.heartbeat_task.cancel()
if self.scheduler_task:
self.scheduler_task.cancel()
# Unregister worker
await self._unregister_worker()
# Close connections
await self.broker.close()
await self.db.close()
logger.info("Worker shutdown complete")
async def _unregister_worker(self):
"""Unregister worker from database."""
async with self.db.acquire() as conn:
await conn.execute(
"DELETE FROM workers WHERE id = $1",
self.worker_id
)
Worker CLI:
import click
import asyncio
@click.command()
@click.option('--queues', '-Q', multiple=True, default=['default'])
@click.option('--concurrency', '-c', default=1, type=int)
@click.option('--hostname', '-n', default=None)
@click.option('--loglevel', '-l', default='INFO')
def worker(queues, concurrency, hostname, loglevel):
"""Start a task worker."""
import logging
logging.basicConfig(
level=getattr(logging, loglevel),
format='%(asctime)s [%(levelname)s] %(message)s'
)
config = WorkerConfig(
worker_name=hostname,
queues=list(queues),
concurrency=concurrency
)
w = TaskWorker(config)
asyncio.run(w.start())
if __name__ == '__main__':
worker()
Acceptance Criteria
- Worker successfully registers on startup
- Worker polls queues and executes tasks
- Concurrency limit is respected
- Heartbeats sent at configured interval
- Graceful shutdown waits for running tasks
- Worker reconnects after connection loss
- Task timeouts are enforced
- Multiple queues supported per worker
Notes
Trade-offs:
- Prefetch vs on-demand: On-demand for simplicity, can add prefetch later
- Process vs thread vs async: Async chosen for Python concurrency
Performance:
- Connection pooling for database operations
- Batch heartbeat updates if needed
Alternatives considered:
- Multi-process worker: Rejected, adds complexity
- Greenlets (gevent): Rejected, not compatible with modern async