File size: 13,866 Bytes
c09f67c | 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | import { Hono } from "hono";
import type {
CreateFlowRequest,
JobStatus,
SortOptions,
TestJobRequest,
} from "../core/types";
import type { WorkbenchCore } from "../core/workbench";
/**
* Parse sort query param in format "field:direction" (e.g., "timestamp:desc")
* Defaults to desc if direction not specified
*/
function parseSort(sort?: string): SortOptions | undefined {
if (!sort) return undefined;
const [field, dir] = sort.split(":");
if (!field) return undefined;
return {
field,
direction: dir === "asc" ? "asc" : "desc",
};
}
/**
* Create API routes for Workbench
*/
export function createApiRoutes(core: WorkbenchCore): Hono {
const app = new Hono();
const qm = core.queueManager;
// POST /api/refresh - Clear all caches (for user-initiated refresh)
app.post("/refresh", async (c) => {
qm.clearCache();
return c.json({ success: true });
});
// GET /api/overview - Dashboard stats
app.get("/overview", async (c) => {
const stats = await qm.getOverview();
return c.json(stats);
});
// GET /api/counts - Lightweight job counts for smart polling
// Returns just total counts per status, very fast (cached)
app.get("/counts", async (c) => {
const counts = await qm.getQuickCounts();
return c.json(counts);
});
// GET /api/runs - All jobs across all queues
// Note: Sorting on non-timestamp fields requires in-memory sort (limited to ~1000 jobs)
// For timestamp sorting, Redis's natural order is used efficiently
app.get("/runs", async (c) => {
const limit = Number(c.req.query("limit")) || 50;
const cursor = c.req.query("cursor");
const start = cursor ? Number(cursor) : 0;
const sort = parseSort(c.req.query("sort"));
// Parse filter parameters
const status = c.req.query("status") as JobStatus | undefined;
const q = c.req.query("q"); // Text search
const from = c.req.query("from"); // Time range start
const to = c.req.query("to"); // Time range end
const tagsParam = c.req.query("tags"); // Tags as JSON string or key:value pairs
// Parse tags filter
let tags: Record<string, string> | undefined;
if (tagsParam) {
try {
// Try parsing as JSON first
tags = JSON.parse(tagsParam);
} catch {
// If not JSON, try parsing as key:value pairs
const tagPairs = tagsParam.split(",");
tags = {};
for (const pair of tagPairs) {
const [key, value] = pair.split(":");
if (key && value) {
tags[key.trim()] = value.trim();
}
}
}
}
// Parse time range
let timeRange: { start: number; end: number } | undefined;
if (from && to) {
timeRange = {
start: Number(from),
end: Number(to),
};
}
// Parse text search from q parameter
// The q parameter might contain both text and tags, so we extract text
let text: string | undefined;
if (q) {
// Simple extraction - if q doesn't contain colons, it's text search
// Otherwise, tags are already parsed above
if (!q.includes(":")) {
text = q;
} else {
// If q contains colons, try to extract text part
// This is a simplified approach - could be enhanced
const parts = q.split(" ");
const textParts = parts.filter((p) => !p.includes(":"));
if (textParts.length > 0) {
text = textParts.join(" ");
}
}
}
const filters =
status || tags || text || timeRange
? {
status,
tags,
text,
timeRange,
}
: undefined;
const result = await qm.getAllRuns(limit, start, sort, filters);
return c.json(result);
});
// GET /api/schedulers - Repeatable and delayed jobs
// Supports separate sort for each table: repeatableSort=name:asc, delayedSort=processAt:desc
app.get("/schedulers", async (c) => {
const repeatableSort = parseSort(c.req.query("repeatableSort"));
const delayedSort = parseSort(c.req.query("delayedSort"));
const result = await qm.getSchedulers(repeatableSort, delayedSort);
return c.json(result);
});
// POST /api/test - Enqueue a test job
app.post("/test", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const body = await c.req.json<TestJobRequest>();
if (!body.queueName || !body.jobName) {
return c.json({ error: "queueName and jobName are required" }, 400);
}
try {
const result = await qm.enqueueJob(body);
return c.json(result);
} catch (e) {
return c.json({ error: (e as Error).message }, 400);
}
});
// GET /api/queue-names - List just queue names (fast, no counts)
app.get("/queue-names", (c) => {
const names = qm.getQueueNames();
return c.json(names);
});
// GET /api/queues - List all queues with counts
app.get("/queues", async (c) => {
const queues = await qm.getQueues();
return c.json(queues);
});
// GET /api/metrics - Get 24-hour metrics
app.get("/metrics", async (c) => {
const metrics = await qm.getMetrics();
return c.json(metrics);
});
// GET /api/activity - Get 7-day activity stats for timeline
app.get("/activity", async (c) => {
const stats = await qm.getActivityStats();
return c.json(stats);
});
// GET /api/queues/:name/jobs - List jobs for a queue
// Note: Sorting on non-timestamp fields requires in-memory sort
app.get("/queues/:name/jobs", async (c) => {
const { name } = c.req.param();
const status = c.req.query("status") as JobStatus | undefined;
const limit = Number(c.req.query("limit")) || 50;
const cursor = c.req.query("cursor");
const start = cursor ? Number(cursor) : 0;
const sort = parseSort(c.req.query("sort"));
const result = await qm.getJobs(name, status, limit, start, sort);
return c.json(result);
});
// GET /api/jobs/:queue/:id - Get single job
app.get("/jobs/:queue/:id", async (c) => {
const { queue, id } = c.req.param();
const job = await qm.getJob(queue, id);
if (!job) {
return c.json({ error: "Job not found" }, 404);
}
return c.json(job);
});
// POST /api/jobs/:queue/:id/retry - Retry a job
app.post("/jobs/:queue/:id/retry", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { queue, id } = c.req.param();
const success = await qm.retryJob(queue, id);
if (!success) {
return c.json({ error: "Failed to retry job" }, 400);
}
return c.json({ success: true });
});
// POST /api/jobs/:queue/:id/remove - Remove a job
app.post("/jobs/:queue/:id/remove", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { queue, id } = c.req.param();
const success = await qm.removeJob(queue, id);
if (!success) {
return c.json({ error: "Failed to remove job" }, 400);
}
return c.json({ success: true });
});
// POST /api/jobs/:queue/:id/promote - Promote a delayed job
app.post("/jobs/:queue/:id/promote", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { queue, id } = c.req.param();
const success = await qm.promoteJob(queue, id);
if (!success) {
return c.json({ error: "Failed to promote job" }, 400);
}
return c.json({ success: true });
});
// GET /api/search - Search jobs
app.get("/search", async (c) => {
const query = c.req.query("q") || "";
const limit = Number(c.req.query("limit")) || 20;
if (!query) {
return c.json({ results: [] });
}
const results = await qm.search(query, limit);
return c.json({ results });
});
// GET /api/tags/:field/values - Get unique values for a tag field
app.get("/tags/:field/values", async (c) => {
const { field } = c.req.param();
const limit = Number(c.req.query("limit")) || 50;
// Check if this is a configured tag field
const tagFields = qm.getTagFields();
if (tagFields.length > 0 && !tagFields.includes(field)) {
return c.json(
{ error: `Field "${field}" is not a configured tag field` },
400,
);
}
const values = await qm.getTagValues(field, limit);
return c.json({ field, values });
});
// POST /api/queues/:name/clean - Clean jobs
app.post("/queues/:name/clean", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { name } = c.req.param();
const body = await c.req.json<{
status: "completed" | "failed";
grace?: number;
}>();
const count = await qm.cleanJobs(name, body.status, body.grace || 0);
return c.json({ removed: count });
});
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Bulk Operations
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// POST /api/bulk/retry - Retry multiple jobs
app.post("/bulk/retry", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const body = await c.req.json<{
jobs: { queueName: string; jobId: string }[];
}>();
const result = await qm.bulkRetry(body.jobs);
return c.json(result);
});
// POST /api/bulk/delete - Delete multiple jobs
app.post("/bulk/delete", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const body = await c.req.json<{
jobs: { queueName: string; jobId: string }[];
}>();
const result = await qm.bulkDelete(body.jobs);
return c.json(result);
});
// POST /api/bulk/promote - Promote multiple delayed jobs
app.post("/bulk/promote", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const body = await c.req.json<{
jobs: { queueName: string; jobId: string }[];
}>();
const result = await qm.bulkPromote(body.jobs);
return c.json(result);
});
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Queue Control (Pause/Resume)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// POST /api/queues/:name/pause - Pause a queue
app.post("/queues/:name/pause", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { name } = c.req.param();
try {
await qm.pauseQueue(name);
return c.json({ success: true, paused: true });
} catch (error) {
return c.json(
{
error:
error instanceof Error ? error.message : "Failed to pause queue",
},
404,
);
}
});
// POST /api/queues/:name/resume - Resume a queue
app.post("/queues/:name/resume", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const { name } = c.req.param();
try {
await qm.resumeQueue(name);
return c.json({ success: true, paused: false });
} catch (error) {
return c.json(
{
error:
error instanceof Error ? error.message : "Failed to resume queue",
},
404,
);
}
});
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Flow Operations
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// GET /api/flows - List all flows
app.get("/flows", async (c) => {
const limit = Number(c.req.query("limit")) || 50;
const flows = await qm.getFlows(limit);
return c.json({ flows });
});
// GET /api/flows/:queueName/:jobId - Get a single flow tree
app.get("/flows/:queueName/:jobId", async (c) => {
const { queueName, jobId } = c.req.param();
const flow = await qm.getFlow(queueName, jobId);
if (!flow) {
return c.json({ error: "Flow not found" }, 404);
}
return c.json(flow);
});
// POST /api/flows - Create a new flow
app.post("/flows", async (c) => {
if (core.options.readonly) {
return c.json({ error: "Dashboard is in readonly mode" }, 403);
}
const body = await c.req.json<CreateFlowRequest>();
if (!body.name || !body.queueName || !body.children?.length) {
return c.json(
{ error: "name, queueName, and children are required" },
400,
);
}
try {
const result = await qm.createFlow(body);
return c.json(result);
} catch (e) {
return c.json({ error: (e as Error).message }, 400);
}
});
return app;
}
|