Spaces:
3SCError404
/
Paused

nexus / api /v1 /worker.py
dushyantsingh0
backend stabilization
4405ca9
Raw History Blame Contribute Delete
4.11 kB
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)) -> Dict[str, Any]:
"""
Returns aggregated stats for worker jobs.
"""
# Count by status
stmt = select(WorkerJob.status, func.count(WorkerJob.id)).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)
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),
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 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(arq_pool: ArqRedis = Depends(get_arq_pool)) -> List[Dict[str, Any]]:
"""
Live query to Redis to find jobs that are currently queued or running.
"""
# Note: arq-specific introspection to find active/queued keys
keys = await arq_pool.keys("arq:job:*")
active_jobs = []
for key in keys:
try:
# arq job keys are bytes, format: arq:job:<job_id>
job_id = key.decode().split(":")[-1]
from arq.jobs import Job
job = Job(job_id, arq_pool)
info = await job.info()
if info:
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