from uuid import UUID from typing import List, Optional, Dict, Any from fastapi import APIRouter, Depends, Query from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, desc, func, String from core.deps import get_db, get_current_super_admin, get_arq_pool from models.worker_job import WorkerJob, JobStatus from arq.connections import ArqRedis router = APIRouter() @router.get("/stats/", dependencies=[Depends(get_current_super_admin)]) async def get_worker_stats( db: AsyncSession = Depends(get_db), workspace_id: Optional[UUID] = None ) -> Dict[str, Any]: """ Returns aggregated stats for worker jobs. """ # Count by status stmt = select(WorkerJob.status, func.count(WorkerJob.id)) if workspace_id: stmt = stmt.where(WorkerJob.metadata_json['workspace_id'].astext == str(workspace_id)) stmt = stmt.group_by(WorkerJob.status) res = await db.execute(stmt) status_counts = {status: count for status, count in res.all()} # Average duration for success jobs avg_stmt = select(func.avg(WorkerJob.duration_ms)).where(WorkerJob.status == JobStatus.SUCCESS) if workspace_id: avg_stmt = avg_stmt.where(WorkerJob.metadata_json['workspace_id'].astext == str(workspace_id)) avg_dur = (await db.execute(avg_stmt)).scalar() or 0.0 return { "status_counts": status_counts, "avg_duration_ms": round(avg_dur, 2), "total_jobs": sum(status_counts.values()) } @router.get("/history/", dependencies=[Depends(get_current_super_admin)]) async def get_job_history( db: AsyncSession = Depends(get_db), workspace_id: Optional[UUID] = None, status: Optional[str] = None, task_name: Optional[str] = None, search: Optional[str] = None, limit: int = Query(10, le=100), page: int = 1 ) -> Dict[str, Any]: """ Retrieves paginated job execution history with metadata. """ offset = (page - 1) * limit # Base query stmt = select(WorkerJob).order_by(desc(WorkerJob.created_at)) count_stmt = select(func.count(WorkerJob.id)) # Apply filters filters = [] if workspace_id: filters.append(WorkerJob.metadata_json['workspace_id'].astext == str(workspace_id)) if status: filters.append(WorkerJob.status == status) if task_name: filters.append(WorkerJob.task_name == task_name) if search: filters.append( (WorkerJob.task_name.ilike(f"%{search}%")) | (WorkerJob.id.cast(String).ilike(f"%{search}%")) ) if filters: stmt = stmt.where(*filters) count_stmt = count_stmt.where(*filters) # Execute count total = (await db.execute(count_stmt)).scalar() or 0 # Execute data query stmt = stmt.limit(limit).offset(offset) res = await db.execute(stmt) jobs = res.scalars().all() pages = (total + limit - 1) // limit return { "items": [ { "id": j.id, "task_name": j.task_name, "status": j.status, "duration_ms": j.duration_ms, "queued_at": j.queued_at, "started_at": j.started_at, "finished_at": j.finished_at, "error": j.error, "args": j.args, "kwargs": j.kwargs, "result": j.result, "metadata": j.metadata_json } for j in jobs ], "total": total, "page": page, "pages": pages, "limit": limit } @router.get("/active/", dependencies=[Depends(get_current_super_admin)]) async def get_active_jobs( workspace_id: Optional[UUID] = None, arq_pool: ArqRedis = Depends(get_arq_pool) ) -> List[Dict[str, Any]]: """ Live query to Redis to find jobs that are currently queued or running. """ active_jobs = [] async for key in arq_pool.scan_iter("arq:job:*"): try: job_id = key.decode().split(":")[-1] from arq.jobs import Job job = Job(job_id, arq_pool) info = await job.info() if info: # If workspace_id is provided, attempt to filter by kwargs or metadata if workspace_id: job_ws = info.kwargs.get('workspace_id') if str(job_ws) != str(workspace_id): continue active_jobs.append({ "id": job_id, "function": info.function, "args": info.args, "enqueue_time": info.enqueue_time, "score": info.score }) except: continue return active_jobs