Spaces:
Paused
Paused
File size: 4,114 Bytes
a27a4ab 4405ca9 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab b5b43d3 a27a4ab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | 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
|