import type { DurableQueue } from "./durable.ts"; import { queueDashboardSnapshot, renderQueueDashboard } from "./scheduler.ts"; export interface QueueAdminOptions { queues: Record; authorize?: (request: Request) => boolean | Promise; } /** Framework-neutral protected queue dashboard/API handler, mountable at any route. */ export function createQueueAdminHandler(options: QueueAdminOptions) { return async (request: Request): Promise => { if (options.authorize && !(await options.authorize(request))) { return Response.json({ error: "Forbidden" }, { status: 403 }); } const url = new URL(request.url); const name = url.searchParams.get("queue") ?? Object.keys(options.queues)[0]; const queue = name ? options.queues[name] : undefined; if (!queue) return Response.json({ error: "Queue not found" }, { status: 404 }); const id = url.searchParams.get("id"); if (request.method === "POST" && id) { const action = url.searchParams.get("action"); const changed = action === "retry" ? await queue.retry(id) : action === "cancel" ? await queue.cancel(id) : false; return Response.json({ ok: changed }); } const snapshot = await queueDashboardSnapshot(queue); if (url.searchParams.get("format") === "json") return Response.json({ queue: name, ...snapshot }); return new Response(renderQueueDashboard(snapshot), { headers: { "content-type": "text/html; charset=utf-8" }, }); }; }