File size: 69,668 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 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 | import { FlowProducer, type Job, type Queue } from "bullmq";
import { LRUCache } from "lru-cache";
import type {
ActivityBucket,
ActivityStatsResponse,
CreateFlowChildRequest,
CreateFlowRequest,
DelayedJobInfo,
FlowNode,
FlowSummary,
HourlyBucket,
JobInfo,
JobStatus,
JobTags,
MetricsResponse,
OverviewStats,
PaginatedResponse,
QueueInfo,
RunInfo,
RunInfoList,
SchedulerInfo,
SearchResult,
SortOptions,
TestJobRequest,
} from "./types";
/**
* Manages queue operations for the Workbench dashboard
*/
export class QueueManager {
private queues: Map<string, Queue> = new Map();
private tagFields: string[] = [];
private flowProducer: FlowProducer | null = null;
// LRU cache for expensive operations
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private cache = new LRUCache<string, any>({
max: 100, // Max 100 entries
ttl: 1000 * 60, // Default 1 minute TTL
allowStale: false, // Don't return stale entries
updateAgeOnGet: true, // Reset TTL on access
});
private readonly CACHE_TTL = {
metrics: 5 * 60 * 1000, // 5 minutes - metrics are expensive
overview: 2 * 60 * 1000, // 2 minutes
queues: 2 * 60 * 1000, // 2 minutes
flows: 2 * 60 * 1000, // 2 minutes
activity: 5 * 60 * 1000, // 5 minutes - activity timeline
};
constructor(queues: Queue[], tagFields: string[] = []) {
for (const queue of queues) {
this.queues.set(queue.name, queue);
}
this.tagFields = tagFields;
// Initialize FlowProducer using connection from first queue
const firstQueue = queues[0];
if (firstQueue) {
const connection = firstQueue.opts?.connection;
if (connection) {
this.flowProducer = new FlowProducer({ connection });
}
}
}
/**
* Get cached value or compute and cache
*/
private async cached<T>(
key: string,
ttl: number,
compute: () => Promise<T>,
): Promise<T> {
const cached = this.cache.get(key);
if (cached !== undefined) {
return cached as T;
}
const data = await compute();
this.cache.set(key, data, { ttl });
return data;
}
/**
* Execute a promise with a timeout
*/
private async withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
errorMessage: string,
): Promise<T> {
return Promise.race([
promise,
new Promise<T>((_, reject) =>
setTimeout(() => reject(new Error(errorMessage)), timeoutMs),
),
]);
}
/**
* Get jobs by time range using Redis sorted sets (ZRANGEBYSCORE)
* This is more efficient than fetching all jobs and filtering in memory
*/
private async getJobsByTimeRange(
queue: Queue,
status: "completed" | "failed",
startTime: number,
endTime: number,
limit: number,
): Promise<Job[]> {
try {
// Access BullMQ's Redis client
const client = (queue as any).client;
if (!client) {
// Fallback to regular getJobs if client not available
const jobs = await queue.getJobs([status], 0, limit * 2);
return jobs.filter(
(job) =>
job.finishedOn &&
job.finishedOn >= startTime &&
job.finishedOn <= endTime,
);
}
// BullMQ stores jobs in sorted sets: bull:queueName:completed, bull:queueName:failed
// The score is the finishedOn timestamp
const queueKey = `bull:${queue.name}:${status}`;
const jobIds = await client.zrangebyscore(
queueKey,
startTime,
endTime,
"LIMIT",
0,
limit,
);
if (!jobIds || jobIds.length === 0) {
return [];
}
// Fetch job data for the IDs in parallel
const jobPromises = jobIds.map((jobId: string) => queue.getJob(jobId));
const jobs = await Promise.all(jobPromises);
// Filter out null/undefined results
return jobs.filter(
(job): job is Job => job !== null && job !== undefined,
);
} catch (_error) {
// Fallback to regular getJobs on error
const jobs = await queue.getJobs([status], 0, limit * 2);
return jobs.filter(
(job) =>
job.finishedOn &&
job.finishedOn >= startTime &&
job.finishedOn <= endTime,
);
}
}
/**
* Cache for job state lookups to avoid repeated Redis calls
*/
private jobStateCache = new LRUCache<string, JobStatus>({
max: 1000,
ttl: 1000 * 30, // 30 second TTL - job states don't change frequently
});
/**
* Cache for job counts to avoid repeated Redis calls
* Short TTL since counts change frequently but are expensive to fetch
*/
private countCache = new LRUCache<
string,
Awaited<ReturnType<Queue["getJobCounts"]>>
>({
max: 100, // Cache counts for up to 100 queues
ttl: 1000 * 5, // 5 second TTL - counts change but not instantly
});
/**
* Get job counts with caching
*/
private async getCachedJobCounts(
queue: Queue,
): Promise<Awaited<ReturnType<Queue["getJobCounts"]>>> {
const cacheKey = queue.name;
const cached = this.countCache.get(cacheKey);
if (cached !== undefined) {
return cached;
}
const counts = await queue.getJobCounts();
this.countCache.set(cacheKey, counts);
return counts;
}
/**
* Invalidate caches related to a job or queue
*/
private invalidateJobCache(queueName: string, jobId?: string): void {
// Invalidate count cache for the queue
this.countCache.delete(queueName);
// Invalidate job state cache if jobId provided
if (jobId) {
const stateCacheKey = `${queueName}:${jobId}`;
this.jobStateCache.delete(stateCacheKey);
}
// Invalidate main cache entries that might be affected
// These are expensive to recompute, so we invalidate them
// to ensure accuracy after mutations
this.cache.delete("metrics");
this.cache.delete("overview");
this.cache.delete("activity");
}
/**
* Clear cache (useful after mutations)
*/
clearCache(prefix?: string): void {
if (prefix) {
for (const key of this.cache.keys()) {
if (key.startsWith(prefix)) {
this.cache.delete(key);
}
}
} else {
this.cache.clear();
}
}
/**
* Get quick job counts across all queues (lightweight, for smart polling)
* Returns total counts per status - cached and very fast
*/
async getQuickCounts(): Promise<{
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
total: number;
timestamp: number;
}> {
// Use short cache for counts - they change frequently
return this.cached("quick-counts", 2000, async () => {
const totals = {
waiting: 0,
active: 0,
completed: 0,
failed: 0,
delayed: 0,
total: 0,
timestamp: Date.now(),
};
await Promise.all(
Array.from(this.queues.values()).map(async (queue) => {
const counts = await this.getCachedJobCounts(queue);
totals.waiting += counts.waiting || 0;
totals.active += counts.active || 0;
totals.completed += counts.completed || 0;
totals.failed += counts.failed || 0;
totals.delayed += counts.delayed || 0;
}),
);
totals.total =
totals.waiting +
totals.active +
totals.completed +
totals.failed +
totals.delayed;
return totals;
});
}
/**
* Get configured tag field names
*/
getTagFields(): string[] {
return this.tagFields;
}
/**
* Get just queue names (very fast, no Redis calls)
* Used for sidebar initial render
*/
getQueueNames(): string[] {
return Array.from(this.queues.keys());
}
/**
* Get a queue by name
*/
getQueue(name: string): Queue | undefined {
return this.queues.get(name);
}
/**
* Get information for all queues (cached)
*/
async getQueues(): Promise<QueueInfo[]> {
return this.cached("queues", this.CACHE_TTL.queues, async () => {
// Parallelize queue info fetching
const queueEntries = Array.from(this.queues.entries());
const results = await Promise.all(
queueEntries.map(async ([name, queue]) => {
const [counts, isPaused] = await Promise.all([
this.getCachedJobCounts(queue),
queue.isPaused(),
]);
return {
name,
counts: {
waiting: counts.waiting || 0,
active: counts.active || 0,
completed: counts.completed || 0,
failed: counts.failed || 0,
delayed: counts.delayed || 0,
paused: counts.paused || 0,
},
isPaused,
};
}),
);
return results;
});
}
/**
* Get overview statistics (cached)
*/
async getOverview(): Promise<OverviewStats> {
return this.cached("overview", this.CACHE_TTL.overview, async () => {
const queues = await this.getQueues();
let totalJobs = 0;
let activeJobs = 0;
let failedJobs = 0;
for (const queue of queues) {
totalJobs +=
queue.counts.waiting + queue.counts.active + queue.counts.delayed;
activeJobs += queue.counts.active;
failedJobs += queue.counts.failed;
}
// Get completed jobs from today (approximation based on completed count)
const completedToday = queues.reduce(
(sum, q) => sum + q.counts.completed,
0,
);
return {
totalJobs,
activeJobs,
failedJobs,
completedToday,
avgDuration: 0, // Would need metrics tracking
queues,
};
});
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Queue Control (Pause/Resume)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Pause a queue - stops processing new jobs
*/
async pauseQueue(queueName: string): Promise<void> {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error(`Queue "${queueName}" not found`);
}
await queue.pause();
}
/**
* Resume a paused queue
*/
async resumeQueue(queueName: string): Promise<void> {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error(`Queue "${queueName}" not found`);
}
await queue.resume();
}
/**
* Check if a queue is paused
*/
async isQueuePaused(queueName: string): Promise<boolean> {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error(`Queue "${queueName}" not found`);
}
return queue.isPaused();
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Metrics
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Get metrics for the last 24 hours (cached - expensive operation)
*/
async getMetrics(): Promise<MetricsResponse> {
return this.cached("metrics", this.CACHE_TTL.metrics, async () => {
return this.withTimeout(
(async () => {
const now = Date.now();
const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;
// Initialize hourly buckets for last 24 hours
const createEmptyBuckets = (): HourlyBucket[] => {
const buckets: HourlyBucket[] = [];
const startHour =
Math.floor(twentyFourHoursAgo / (60 * 60 * 1000)) *
(60 * 60 * 1000);
for (let i = 0; i < 24; i++) {
buckets.push({
hour: startHour + i * 60 * 60 * 1000,
completed: 0,
failed: 0,
avgDuration: 0,
avgWaitTime: 0,
});
}
return buckets;
};
const queueMetricsMap = new Map<
string,
{
buckets: HourlyBucket[];
durations: number[][];
waitTimes: number[][];
}
>();
// Initialize per-queue metrics
for (const queueName of this.queues.keys()) {
queueMetricsMap.set(queueName, {
buckets: createEmptyBuckets(),
durations: Array.from({ length: 24 }, () => []),
waitTimes: Array.from({ length: 24 }, () => []),
});
}
// Track slowest jobs and failing job types
const allJobs: Array<{
name: string;
queueName: string;
duration: number;
jobId: string;
}> = [];
const jobTypeStats = new Map<
string,
{
name: string;
queueName: string;
completed: number;
failed: number;
}
>();
// Fetch completed and failed jobs from each queue IN PARALLEL
// Use time-based filtering to only get jobs within the 24-hour window
const queueEntries = Array.from(this.queues.entries());
// First, check which queues have relevant jobs using getJobCounts
const queueChecks = await Promise.all(
queueEntries.map(async ([queueName, queue]) => {
const counts = await this.getCachedJobCounts(queue);
return {
queueName,
queue,
hasRelevantJobs:
(counts.completed || 0) > 0 || (counts.failed || 0) > 0,
};
}),
);
// Only process queues with relevant jobs
const relevantQueues = queueChecks.filter((q) => q.hasRelevantJobs);
const queueResults = await Promise.all(
relevantQueues.map(async ({ queueName, queue }) => {
// Use time-based filtering - only fetch jobs within the 24-hour window
// Reduced limit since we're filtering by time in Redis
const [completedJobs, failedJobs] = await Promise.all([
this.getJobsByTimeRange(
queue,
"completed",
twentyFourHoursAgo,
now,
100, // Reduced from 200 - only recent jobs needed
),
this.getJobsByTimeRange(
queue,
"failed",
twentyFourHoursAgo,
now,
100, // Reduced from 200 - only recent jobs needed
),
]);
return { queueName, completedJobs, failedJobs };
}),
);
// Process results
for (const { queueName, completedJobs, failedJobs } of queueResults) {
const metrics = queueMetricsMap.get(queueName)!;
// Process completed jobs
for (const job of completedJobs) {
if (
!job ||
!job.finishedOn ||
job.finishedOn < twentyFourHoursAgo
)
continue;
const bucketIndex = Math.floor(
(job.finishedOn - (metrics.buckets[0]?.hour || 0)) /
(60 * 60 * 1000),
);
if (bucketIndex >= 0 && bucketIndex < 24) {
metrics.buckets[bucketIndex].completed++;
const duration = job.processedOn
? job.finishedOn - job.processedOn
: 0;
const waitTime = job.processedOn
? job.processedOn - job.timestamp
: 0;
if (duration > 0) {
metrics.durations[bucketIndex].push(duration);
allJobs.push({
name: job.name,
queueName,
duration,
jobId: job.id || "",
});
}
if (waitTime > 0) {
metrics.waitTimes[bucketIndex].push(waitTime);
}
}
// Track job type stats
const key = `${queueName}:${job.name}`;
const stats = jobTypeStats.get(key) || {
name: job.name,
queueName,
completed: 0,
failed: 0,
};
stats.completed++;
jobTypeStats.set(key, stats);
}
// Process failed jobs
for (const job of failedJobs) {
if (
!job ||
!job.finishedOn ||
job.finishedOn < twentyFourHoursAgo
)
continue;
const bucketIndex = Math.floor(
(job.finishedOn - (metrics.buckets[0]?.hour || 0)) /
(60 * 60 * 1000),
);
if (bucketIndex >= 0 && bucketIndex < 24) {
metrics.buckets[bucketIndex].failed++;
}
// Track job type stats
const key = `${queueName}:${job.name}`;
const stats = jobTypeStats.get(key) || {
name: job.name,
queueName,
completed: 0,
failed: 0,
};
stats.failed++;
jobTypeStats.set(key, stats);
}
}
// Calculate averages for each bucket
for (const metrics of queueMetricsMap.values()) {
for (let i = 0; i < 24; i++) {
const durations = metrics.durations[i];
const waitTimes = metrics.waitTimes[i];
if (durations.length > 0) {
metrics.buckets[i].avgDuration = Math.round(
durations.reduce((a, b) => a + b, 0) / durations.length,
);
}
if (waitTimes.length > 0) {
metrics.buckets[i].avgWaitTime = Math.round(
waitTimes.reduce((a, b) => a + b, 0) / waitTimes.length,
);
}
}
}
// Skip per-queue metrics - not used by frontend (only aggregate is displayed)
// Return empty array to maintain API compatibility
// Build aggregate metrics
const aggregateBuckets = createEmptyBuckets();
const aggregateDurations: number[][] = Array.from(
{ length: 24 },
() => [],
);
const aggregateWaitTimes: number[][] = Array.from(
{ length: 24 },
() => [],
);
for (const metrics of queueMetricsMap.values()) {
for (let i = 0; i < 24; i++) {
aggregateBuckets[i].completed += metrics.buckets[i].completed;
aggregateBuckets[i].failed += metrics.buckets[i].failed;
aggregateDurations[i].push(...metrics.durations[i]);
aggregateWaitTimes[i].push(...metrics.waitTimes[i]);
}
}
// Calculate aggregate averages
for (let i = 0; i < 24; i++) {
if (aggregateDurations[i].length > 0) {
aggregateBuckets[i].avgDuration = Math.round(
aggregateDurations[i].reduce((a, b) => a + b, 0) /
aggregateDurations[i].length,
);
}
if (aggregateWaitTimes[i].length > 0) {
aggregateBuckets[i].avgWaitTime = Math.round(
aggregateWaitTimes[i].reduce((a, b) => a + b, 0) /
aggregateWaitTimes[i].length,
);
}
}
const totalCompleted = aggregateBuckets.reduce(
(sum, b) => sum + b.completed,
0,
);
const totalFailed = aggregateBuckets.reduce(
(sum, b) => sum + b.failed,
0,
);
const allDurations = aggregateDurations.flat();
const allWaitTimes = aggregateWaitTimes.flat();
// Get top 10 slowest jobs
const slowestJobs = allJobs
.sort((a, b) => b.duration - a.duration)
.slice(0, 10);
// Get top 10 most failing job types
const mostFailingTypes = Array.from(jobTypeStats.values())
.filter((s) => s.failed > 0)
.map((s) => ({
name: s.name,
queueName: s.queueName,
failCount: s.failed,
totalCount: s.completed + s.failed,
errorRate: s.failed / (s.completed + s.failed),
}))
.sort((a, b) => b.failCount - a.failCount)
.slice(0, 10);
return {
queues: [], // Empty - per-queue metrics not used by frontend
aggregate: {
queueName: "all",
buckets: aggregateBuckets,
summary: {
totalCompleted,
totalFailed,
errorRate:
totalCompleted + totalFailed > 0
? totalFailed / (totalCompleted + totalFailed)
: 0,
avgDuration:
allDurations.length > 0
? Math.round(
allDurations.reduce((a, b) => a + b, 0) /
allDurations.length,
)
: 0,
avgWaitTime:
allWaitTimes.length > 0
? Math.round(
allWaitTimes.reduce((a, b) => a + b, 0) /
allWaitTimes.length,
)
: 0,
throughputPerHour: Math.round(
(totalCompleted + totalFailed) / 24,
),
},
},
slowestJobs,
mostFailingTypes,
computedAt: now,
};
})(),
45000, // 45 second timeout (before proxy timeout)
"Metrics computation timed out after 45 seconds",
);
});
}
/**
* Get activity stats for the last 7 days (cached)
* Returns 4-hour buckets for the activity timeline
*/
async getActivityStats(): Promise<ActivityStatsResponse> {
return this.cached("activity", this.CACHE_TTL.activity, async () => {
const now = Date.now();
const bucketSize = 4 * 60 * 60 * 1000; // 4 hours
const bucketCount = 42; // 7 days * 6 buckets per day
// Start from midnight 7 days ago
const startDate = new Date(now);
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - 6);
const startTime = startDate.getTime();
// Initialize buckets
const buckets: ActivityBucket[] = [];
for (let i = 0; i < bucketCount; i++) {
buckets.push({
time: startTime + i * bucketSize,
completed: 0,
failed: 0,
});
}
// Fetch completed and failed jobs from each queue IN PARALLEL
// Use time-based filtering to only get jobs within the 7-day window
const queueEntries = Array.from(this.queues.entries());
// First, check which queues have relevant jobs
const queueChecks = await Promise.all(
queueEntries.map(async ([, queue]) => {
const counts = await this.getCachedJobCounts(queue);
return {
queue,
hasRelevantJobs:
(counts.completed || 0) > 0 || (counts.failed || 0) > 0,
};
}),
);
// Only process queues with relevant jobs
const relevantQueues = queueChecks.filter((q) => q.hasRelevantJobs);
const queueResults = await Promise.all(
relevantQueues.map(async ({ queue }) => {
// Use time-based filtering - only fetch jobs within the 7-day window
// Reduced limit since we're filtering by time in Redis
const [completedJobs, failedJobs] = await Promise.all([
this.getJobsByTimeRange(
queue,
"completed",
startTime,
now,
200, // Reduced from 500 - only jobs in time range needed
),
this.getJobsByTimeRange(
queue,
"failed",
startTime,
now,
200, // Reduced from 500 - only jobs in time range needed
),
]);
return { completedJobs, failedJobs };
}),
);
// Process results
for (const { completedJobs, failedJobs } of queueResults) {
// Process completed jobs
for (const job of completedJobs) {
if (!job || !job.finishedOn || job.finishedOn < startTime) continue;
const bucketIndex = Math.floor(
(job.finishedOn - startTime) / bucketSize,
);
if (bucketIndex >= 0 && bucketIndex < bucketCount) {
buckets[bucketIndex].completed++;
}
}
// Process failed jobs
for (const job of failedJobs) {
if (!job || !job.finishedOn || job.finishedOn < startTime) continue;
const bucketIndex = Math.floor(
(job.finishedOn - startTime) / bucketSize,
);
if (bucketIndex >= 0 && bucketIndex < bucketCount) {
buckets[bucketIndex].failed++;
}
}
}
const totalCompleted = buckets.reduce((sum, b) => sum + b.completed, 0);
const totalFailed = buckets.reduce((sum, b) => sum + b.failed, 0);
return {
buckets,
startTime,
endTime: now,
bucketSize,
totalCompleted,
totalFailed,
computedAt: now,
};
});
}
/**
* Get jobs for a specific queue with pagination and sorting
*/
async getJobs(
queueName: string,
status?: JobStatus,
limit = 50,
start = 0,
sort?: SortOptions,
): Promise<PaginatedResponse<JobInfo>> {
const queue = this.queues.get(queueName);
if (!queue) {
return { data: [], total: 0, hasMore: false };
}
const types = status
? [status]
: ["waiting", "active", "completed", "failed", "delayed"];
// Fetch counts once before the loop (same for all types in a queue)
const counts = await this.getCachedJobCounts(queue);
// Track jobs with their known state to avoid getState() calls
const jobsWithState: { job: Job; state: JobStatus }[] = [];
let total = 0;
for (const type of types) {
const typeJobs = await queue.getJobs(type as any, start, start + limit);
jobsWithState.push(
...typeJobs.map((job) => ({ job, state: type as JobStatus })),
);
const typeCount = counts[type as keyof typeof counts] || 0;
total += typeCount;
}
// Convert to JobInfo - pass known state to skip expensive getState() calls
const jobInfos = (await Promise.all(
jobsWithState.map(({ job, state }) => this.jobToInfo(job, "full", state)),
)) as JobInfo[];
// Apply sorting
const sortField = sort?.field ?? "timestamp";
const sortDir = sort?.direction === "asc" ? 1 : -1;
jobInfos.sort((a, b) => {
const aVal = this.getSortValue(a, sortField);
const bVal = this.getSortValue(b, sortField);
if (aVal < bVal) return -1 * sortDir;
if (aVal > bVal) return 1 * sortDir;
return 0;
});
// Take only the requested limit
const data = jobInfos.slice(0, limit);
return {
data,
total,
hasMore: start + limit < total,
cursor: start + limit < total ? String(start + limit) : undefined,
};
}
/**
* Get a single job by ID
*/
async getJob(queueName: string, jobId: string): Promise<JobInfo | null> {
const queue = this.queues.get(queueName);
if (!queue) return null;
const job = await queue.getJob(jobId);
if (!job) return null;
return this.jobToInfo(job, "full") as Promise<JobInfo>;
}
/**
* Retry a failed job
*/
async retryJob(queueName: string, jobId: string): Promise<boolean> {
const queue = this.queues.get(queueName);
if (!queue) return false;
const job = await queue.getJob(jobId);
if (!job) return false;
await job.retry();
this.invalidateJobCache(queueName, jobId);
return true;
}
/**
* Remove a job
*/
async removeJob(queueName: string, jobId: string): Promise<boolean> {
const queue = this.queues.get(queueName);
if (!queue) return false;
const job = await queue.getJob(jobId);
if (!job) return false;
await job.remove();
this.invalidateJobCache(queueName, jobId);
return true;
}
/**
* Promote a delayed job to waiting
*/
async promoteJob(queueName: string, jobId: string): Promise<boolean> {
const queue = this.queues.get(queueName);
if (!queue) return false;
const job = await queue.getJob(jobId);
if (!job) return false;
await job.promote();
this.invalidateJobCache(queueName, jobId);
return true;
}
/**
* Parse search query for field:value filters
* Returns { filters: { field: value }, text: remainingText }
*/
private parseSearchQuery(query: string): {
filters: Record<string, string>;
text: string;
} {
const filters: Record<string, string> = {};
const parts: string[] = [];
// Match field:value patterns (supporting quoted values)
const regex = /(\w+):(?:"([^"]+)"|(\S+))/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while (true) {
match = regex.exec(query);
if (!match) break;
// Add any text before this match
if (match.index > lastIndex) {
parts.push(query.slice(lastIndex, match.index).trim());
}
const field = match[1];
const value = match[2] || match[3]; // quoted or unquoted value
filters[field] = value;
lastIndex = regex.lastIndex;
}
// Add remaining text after last match
if (lastIndex < query.length) {
parts.push(query.slice(lastIndex).trim());
}
return {
filters,
text: parts.filter(Boolean).join(" "),
};
}
/**
* Check if a raw job matches all provided filters (before conversion)
* This is more efficient than converting to JobInfo first
*/
private jobMatchesAllFilters(
job: Job,
filters: {
status?: JobStatus;
tags?: Record<string, string>;
text?: string;
timeRange?: { start: number; end: number };
},
): boolean {
// Status filter is handled by fetching only the requested status types
// So we don't need to check it here - jobs are already filtered by type
// Check time range filter (cheap - uses raw timestamps)
if (filters.timeRange) {
const jobTime = job.processedOn || job.finishedOn || job.timestamp || 0;
if (
jobTime < filters.timeRange.start ||
jobTime > filters.timeRange.end
) {
return false;
}
}
// Check tag filters (extract only needed fields from job.data)
if (filters.tags && Object.keys(filters.tags).length > 0) {
if (!job.data || typeof job.data !== "object") {
return false;
}
const dataObj = job.data as Record<string, unknown>;
for (const [field, value] of Object.entries(filters.tags)) {
const jobValue = dataObj[field];
if (jobValue === undefined || jobValue === null) {
return false;
}
// Case-insensitive comparison for strings
const strJobValue = String(jobValue).toLowerCase();
const strFilterValue = value.toLowerCase();
if (!strJobValue.includes(strFilterValue)) {
return false;
}
}
}
// Check text search (only stringify if needed)
if (filters.text) {
const lowerText = filters.text.toLowerCase();
const matchesId = job.id?.toLowerCase().includes(lowerText);
const matchesName = job.name?.toLowerCase().includes(lowerText);
if (!matchesId && !matchesName) {
// Only stringify job.data if ID and name don't match
const stringifiedData = JSON.stringify(job.data).toLowerCase();
if (!stringifiedData.includes(lowerText)) {
return false;
}
}
}
return true;
}
/**
* Check if a job matches the given tag filters
*/
private jobMatchesFilters(
job: Job,
filters: Record<string, string>,
): boolean {
if (!job.data || typeof job.data !== "object") {
return Object.keys(filters).length === 0;
}
const dataObj = job.data as Record<string, unknown>;
for (const [field, value] of Object.entries(filters)) {
const jobValue = dataObj[field];
if (jobValue === undefined || jobValue === null) {
return false;
}
// Case-insensitive comparison for strings
const strJobValue = String(jobValue).toLowerCase();
const strFilterValue = value.toLowerCase();
if (!strJobValue.includes(strFilterValue)) {
return false;
}
}
return true;
}
/**
* Search jobs across all queues
* Supports field:value syntax (e.g., "teamId:abc-123 invoice")
* Optimized with parallel processing, early exits, and count checks
*/
async search(query: string, limit = 20): Promise<SearchResult[]> {
const { filters, text } = this.parseSearchQuery(query);
const lowerText = text.toLowerCase();
const hasFilters = Object.keys(filters).length > 0;
const hasText = lowerText.length > 0;
// Early exit if no search criteria
if (!hasFilters && !hasText) {
return [];
}
// Check counts first to skip empty queues
const queueEntries = Array.from(this.queues.entries());
const queueChecks = await Promise.all(
queueEntries.map(async ([queueName, queue]) => {
const counts = await this.getCachedJobCounts(queue);
const hasJobs =
(counts.waiting || 0) > 0 ||
(counts.active || 0) > 0 ||
(counts.completed || 0) > 0 ||
(counts.failed || 0) > 0 ||
(counts.delayed || 0) > 0;
return { queueName, queue, hasJobs };
}),
);
const relevantQueues = queueChecks.filter((q) => q.hasJobs);
if (relevantQueues.length === 0) {
return [];
}
// Process all queues in parallel instead of sequentially
const types = ["waiting", "active", "completed", "failed", "delayed"];
const fetchLimit = Math.min(limit * 2, 50); // Reduced from 100 - only fetch what we need
// WeakMap for caching stringified job data
const stringifiedDataCache = new WeakMap<Job, string>();
// Process all queues concurrently
const queueResults = await Promise.allSettled(
relevantQueues.map(async ({ queueName, queue }) => {
// Search in all job states in parallel
const typeResults = await Promise.all(
types.map(async (type) => {
try {
const jobs = await queue.getJobs(type as any, 0, fetchLimit);
const matches: SearchResult[] = [];
for (const job of jobs) {
// Check field:value filters first
if (hasFilters && !this.jobMatchesFilters(job, filters)) {
continue;
}
// If there's text search, match by job ID, name, or data
if (hasText) {
const matchesId = job.id?.toLowerCase().includes(lowerText);
const matchesName = job.name
?.toLowerCase()
.includes(lowerText);
// Only stringify if ID and name don't match (expensive operation)
let matchesData = false;
if (!matchesId && !matchesName) {
// Use cached stringified data if available
let stringifiedData = stringifiedDataCache.get(job);
if (!stringifiedData) {
stringifiedData = JSON.stringify(job.data).toLowerCase();
stringifiedDataCache.set(job, stringifiedData);
}
matchesData = stringifiedData.includes(lowerText);
}
if (!matchesId && !matchesName && !matchesData) {
continue;
}
}
// Pass known state to skip expensive getState() calls
matches.push({
queue: queueName,
job: (await this.jobToInfo(
job,
"full",
type as JobStatus,
)) as JobInfo,
});
}
return matches;
} catch {
return [];
}
}),
);
return typeResults.flat();
}),
);
// Collect all matches from all queues
const allMatches: SearchResult[] = [];
for (const result of queueResults) {
if (result.status === "fulfilled") {
allMatches.push(...result.value);
}
}
// Return limited results
return allMatches.slice(0, limit);
}
/**
* Clean jobs from a queue
*/
async cleanJobs(
queueName: string,
status: "completed" | "failed",
grace = 0,
): Promise<number> {
const queue = this.queues.get(queueName);
if (!queue) return 0;
const removed = await queue.clean(grace, 1000, status);
return removed.length;
}
/**
* FAST PATH: Get latest runs without filters
* Optimized for the common case of viewing newest jobs (timestamp desc, no filters)
* - Single getJobs call per queue (not per status type)
* - No count checks needed
* - Minimal Redis round-trips
*/
private async getLatestRuns(
limit: number,
start: number,
): Promise<PaginatedResponse<RunInfoList>> {
const queueEntries = Array.from(this.queues.entries());
const numQueues = queueEntries.length;
if (numQueues === 0) {
return { data: [], total: -1, hasMore: false, cursor: undefined };
}
// Fetch a small number of recent jobs from each queue
// We need enough to fill the page after sorting by timestamp
const perQueueFetch = Math.max(5, Math.ceil((limit + 10) / numQueues) + 2);
// Fetch from all queues in parallel - single call per queue with all types
const allTypes: JobStatus[] = [
"waiting",
"active",
"completed",
"failed",
"delayed",
];
const results = await Promise.all(
queueEntries.map(async ([queueName, queue]) => {
// Single getJobs call with all types - much faster than 5 separate calls
const jobs = await queue.getJobs(allTypes as any, 0, perQueueFetch);
return jobs.map((job) => ({ job, queueName }));
}),
);
// Flatten and sort by timestamp desc
const allJobs = results.flat();
allJobs.sort((a, b) => {
const timeDiff = (b.job.timestamp || 0) - (a.job.timestamp || 0);
if (timeDiff !== 0) return timeDiff;
// Secondary sort for stability
return a.queueName.localeCompare(b.queueName);
});
// Apply pagination
const jobsToConvert = allJobs.slice(start, start + limit);
// Convert to RunInfoList - infer state from job properties
const runInfos = await Promise.all(
jobsToConvert.map(async ({ job, queueName }) => {
// Infer state from job properties to avoid getState() Redis call
let state: JobStatus = "waiting";
if (job.finishedOn) {
state = job.failedReason ? "failed" : "completed";
} else if (job.processedOn) {
state = "active";
} else if (job.delay && job.delay > 0) {
state = "delayed";
}
const info = await this.jobToInfo(job, "list", state);
return { ...info, queueName } as RunInfoList;
}),
);
// Determine if there are more results
const hasMore = allJobs.length > start + limit;
return {
data: runInfos,
total: -1, // Don't calculate total for fast path - not needed for UI
hasMore,
cursor: hasMore ? String(start + runInfos.length) : undefined,
};
}
/**
* Get all runs (jobs) across all queues with sorting and filtering
* Uses fast path for common case (no filters, timestamp desc)
*/
async getAllRuns(
limit = 50,
start = 0,
sort?: SortOptions,
filters?: {
status?: JobStatus;
tags?: Record<string, string>;
text?: string;
timeRange?: { start: number; end: number };
},
): Promise<PaginatedResponse<RunInfoList>> {
const sortField = sort?.field ?? "timestamp";
const sortDir = sort?.direction === "asc" ? 1 : -1;
const hasFilters = !!(
filters?.status ||
filters?.tags ||
filters?.text ||
filters?.timeRange
);
const isTimestampSort = sortField === "timestamp";
// FAST PATH: No filters, timestamp desc = just get newest jobs
// This is the most common use case and should be instant
if (!hasFilters && isTimestampSort && sortDir === -1) {
return this.getLatestRuns(limit, start);
}
// FILTERED PATH: More complex queries need full filtering logic
const queueEntries = Array.from(this.queues.entries());
// Determine which job types to fetch based on status filter
const types = filters?.status
? [filters.status]
: ["waiting", "active", "completed", "failed", "delayed"];
const hasTimeRange = !!filters?.timeRange;
const numQueues = Math.max(queueEntries.length, 1);
if (queueEntries.length === 0) {
return {
data: [],
total: 0,
hasMore: false,
cursor: undefined,
};
}
// For filtered queries, fetch enough to likely fill one page after filtering
// Reduced from 50 to be smarter about distribution
const baseFetchPerQueue = Math.max(
Math.ceil((limit * 2) / numQueues) + 3,
5,
);
let allJobs: { job: Job; queueName: string; state: JobStatus }[] = [];
// Helper function to fetch from a single queue
const fetchFromQueue = async (
queueName: string,
queue: Queue,
fetchCount: number,
) => {
// Use time-range queries for completed/failed jobs when time range is specified
if (hasTimeRange && filters?.timeRange) {
const timeRangeJobs: { job: Job; state: JobStatus }[] = [];
// Use efficient time-range queries for completed/failed
if (types.includes("completed")) {
const completedJobs = await this.getJobsByTimeRange(
queue,
"completed",
filters.timeRange.start,
filters.timeRange.end,
fetchCount,
);
timeRangeJobs.push(
...completedJobs.map((job) => ({
job,
state: "completed" as JobStatus,
})),
);
}
if (types.includes("failed")) {
const failedJobs = await this.getJobsByTimeRange(
queue,
"failed",
filters.timeRange.start,
filters.timeRange.end,
fetchCount,
);
timeRangeJobs.push(
...failedJobs.map((job) => ({
job,
state: "failed" as JobStatus,
})),
);
}
// For other types, use regular getJobs
const otherTypes = types.filter(
(t) => t !== "completed" && t !== "failed",
);
if (otherTypes.length > 0) {
const otherJobArrays = await Promise.all(
otherTypes.map(async (type) => {
const jobs = await queue.getJobs(type as any, 0, fetchCount);
return jobs.map((job) => ({ job, state: type as JobStatus }));
}),
);
timeRangeJobs.push(...otherJobArrays.flat());
}
return timeRangeJobs.map(({ job, state }) => ({
job,
queueName,
state,
}));
}
// For status filter, only fetch that type
if (filters?.status) {
const jobs = await queue.getJobs(filters.status as any, 0, fetchCount);
return jobs.map((job) => ({
job,
queueName,
state: filters.status as JobStatus,
}));
}
// Regular fetching for all types - track state for each type
const jobArrays = await Promise.all(
types.map(async (type) => {
const jobs = await queue.getJobs(type as any, 0, fetchCount);
return jobs.map((job) => ({ job, state: type as JobStatus }));
}),
);
return jobArrays
.flat()
.map(({ job, state }) => ({ job, queueName, state }));
};
// Fetch from ALL queues in parallel
const results = await Promise.all(
queueEntries.map(([queueName, queue]) =>
fetchFromQueue(queueName, queue, baseFetchPerQueue),
),
);
allJobs = results.flat();
// Apply filters BEFORE sorting and pagination
if (filters) {
allJobs = allJobs.filter(({ job }) =>
this.jobMatchesAllFilters(job, filters),
);
}
// Sort all filtered jobs to ensure consistent ordering
// sortDir: 1 = asc (oldest first), -1 = desc (newest first, default)
if (isTimestampSort) {
allJobs.sort((a, b) => {
const aTime = a.job.timestamp || 0;
const bTime = b.job.timestamp || 0;
// Primary sort by timestamp
const timeDiff = sortDir === -1 ? bTime - aTime : aTime - bTime;
if (timeDiff !== 0) return timeDiff;
// Secondary sort by queueName for stability
const queueDiff = a.queueName.localeCompare(b.queueName);
if (queueDiff !== 0) return queueDiff;
// Tertiary sort by job ID for complete stability
return (a.job.id || "").localeCompare(b.job.id || "");
});
}
// Apply pagination
const jobsToConvert = allJobs.slice(start, start + limit);
// Convert only the jobs we'll return
const runInfos = await Promise.all(
jobsToConvert.map(async ({ job, queueName, state }) => {
const info = await this.jobToInfo(job, "list", state);
return { ...info, queueName } as RunInfoList;
}),
);
// For non-timestamp sorting, sort after conversion
if (!isTimestampSort) {
runInfos.sort((a, b) => {
const aVal = this.getSortValueForList(a, sortField);
const bVal = this.getSortValueForList(b, sortField);
if (aVal < bVal) return -1 * sortDir;
if (aVal > bVal) return 1 * sortDir;
return 0;
});
}
// Build cursor for next page
const hasMore = allJobs.length > start + limit;
return {
data: runInfos,
total: -1, // Don't calculate total - not needed for UI
hasMore,
cursor: hasMore ? String(start + runInfos.length) : undefined,
};
}
/**
* Get all schedulers (repeatable and delayed jobs) with sorting
*/
async getSchedulers(
repeatableSort?: SortOptions,
delayedSort?: SortOptions,
): Promise<{
repeatable: SchedulerInfo[];
delayed: DelayedJobInfo[];
}> {
const repeatable: SchedulerInfo[] = [];
const delayed: DelayedJobInfo[] = [];
// Fetch from all queues in parallel
const queueEntries = Array.from(this.queues.entries());
const results = await Promise.all(
queueEntries.map(async ([queueName, queue]) => {
const [repeatableJobs, delayedJobs] = await Promise.all([
queue.getRepeatableJobs(),
queue.getJobs("delayed", 0, 50),
]);
return { queueName, repeatableJobs, delayedJobs };
}),
);
// Process results
for (const { queueName, repeatableJobs, delayedJobs } of results) {
for (const job of repeatableJobs) {
repeatable.push({
key: job.key,
name: job.name || "unnamed",
queueName,
pattern: job.pattern ?? undefined,
every: job.every ? Number(job.every) : undefined,
next: job.next ?? undefined,
endDate: job.endDate ?? undefined,
tz: job.tz ?? undefined,
});
}
for (const job of delayedJobs) {
const delay = job.opts.delay || 0;
delayed.push({
id: job.id || "",
name: job.name,
queueName,
delay,
processAt: job.timestamp + delay,
data: job.data,
});
}
}
// Sort repeatable jobs
const repeatableField = repeatableSort?.field ?? "name";
const repeatableDir = repeatableSort?.direction === "desc" ? -1 : 1;
repeatable.sort((a, b) => {
const aVal = this.getSchedulerSortValue(a, repeatableField);
const bVal = this.getSchedulerSortValue(b, repeatableField);
if (aVal < bVal) return -1 * repeatableDir;
if (aVal > bVal) return 1 * repeatableDir;
return 0;
});
// Sort delayed jobs
const delayedField = delayedSort?.field ?? "processAt";
const delayedDir = delayedSort?.direction === "desc" ? -1 : 1;
delayed.sort((a, b) => {
const aVal = this.getDelayedSortValue(a, delayedField);
const bVal = this.getDelayedSortValue(b, delayedField);
if (aVal < bVal) return -1 * delayedDir;
if (aVal > bVal) return 1 * delayedDir;
return 0;
});
return { repeatable, delayed };
}
/**
* Enqueue a new job (for testing)
*/
async enqueueJob(request: TestJobRequest): Promise<{ id: string }> {
const queue = this.queues.get(request.queueName);
if (!queue) {
throw new Error(`Queue "${request.queueName}" not found`);
}
const job = await queue.add(request.jobName, request.data, {
delay: request.opts?.delay,
priority: request.opts?.priority,
attempts: request.opts?.attempts,
});
return { id: job.id || "" };
}
/**
* Extract tag values from job data based on configured tag fields
*/
private extractTags(data: unknown): JobTags | undefined {
if (!this.tagFields.length || !data || typeof data !== "object") {
return undefined;
}
const tags: JobTags = {};
const dataObj = data as Record<string, unknown>;
for (const field of this.tagFields) {
const value = dataObj[field];
if (
value !== undefined &&
(typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
value === null)
) {
tags[field] = value as string | number | boolean | null;
}
}
return Object.keys(tags).length > 0 ? tags : undefined;
}
/**
* Get unique values for a specific tag field across all jobs
*/
async getTagValues(
field: string,
limit = 50,
): Promise<{ value: string; count: number }[]> {
const valueMap = new Map<string, number>();
const types = ["waiting", "active", "completed", "failed", "delayed"];
// Fetch jobs from all queues in parallel
const queueEntries = Array.from(this.queues.entries());
const queueResults = await Promise.all(
queueEntries.map(async ([, queue]) => {
const jobArrays = await Promise.all(
types.map((type) => queue.getJobs(type as any, 0, 100)),
);
return jobArrays.flat();
}),
);
// Process all jobs
for (const jobs of queueResults) {
for (const job of jobs) {
if (job.data && typeof job.data === "object") {
const dataObj = job.data as Record<string, unknown>;
const value = dataObj[field];
if (value !== undefined && value !== null) {
const strValue = String(value);
valueMap.set(strValue, (valueMap.get(strValue) || 0) + 1);
}
}
}
}
// Sort by count descending and take top N
const sorted = Array.from(valueMap.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([value, count]) => ({ value, count }));
return sorted;
}
/**
* Get sortable value from JobInfo/RunInfo
*/
private getSortValue(
item: JobInfo | RunInfo,
field: string,
): string | number {
switch (field) {
case "timestamp":
return item.timestamp ?? 0;
case "name":
return item.name.toLowerCase();
case "status":
return item.status;
case "duration":
return item.duration ?? 0;
case "queueName":
return "queueName" in item ? item.queueName.toLowerCase() : "";
case "processedOn":
return item.processedOn ?? 0;
default:
return item.timestamp ?? 0;
}
}
/**
* Get sortable value from RunInfoList (lightweight version)
*/
private getSortValueForList(
item: RunInfoList,
field: string,
): string | number {
switch (field) {
case "timestamp":
return item.timestamp ?? 0;
case "name":
return item.name.toLowerCase();
case "status":
return item.status;
case "duration":
return item.duration ?? 0;
case "queueName":
return item.queueName.toLowerCase();
case "processedOn":
return item.processedOn ?? 0;
default:
return item.timestamp ?? 0;
}
}
/**
* Get sortable value from SchedulerInfo
*/
private getSchedulerSortValue(
item: SchedulerInfo,
field: string,
): string | number {
switch (field) {
case "name":
return item.name.toLowerCase();
case "queueName":
return item.queueName.toLowerCase();
case "pattern":
return item.pattern?.toLowerCase() ?? "";
case "next":
return item.next ?? 0;
case "tz":
return item.tz?.toLowerCase() ?? "";
default:
return item.name.toLowerCase();
}
}
/**
* Get sortable value from DelayedJobInfo
*/
private getDelayedSortValue(
item: DelayedJobInfo,
field: string,
): string | number {
switch (field) {
case "name":
return item.name.toLowerCase();
case "queueName":
return item.queueName.toLowerCase();
case "processAt":
return item.processAt;
case "delay":
return item.delay;
default:
return item.processAt;
}
}
/**
* Convert a BullMQ Job to JobInfo or RunInfoList
* @param job - The BullMQ job to convert
* @param fields - "list" for lightweight list view, "full" for complete job details
* @param knownState - Optional: skip getState() call if state is already known from fetch
*/
private async jobToInfo(
job: Job,
_fields: "list" | "full" = "full",
knownState?: JobStatus,
): Promise<JobInfo | RunInfoList> {
// Use known state if provided (avoids expensive Redis getState() call)
// Otherwise use cached state, or fetch and cache
let state = knownState;
if (!state) {
const cacheKey = `${job.queueName}:${job.id}`;
state = this.jobStateCache.get(cacheKey);
if (!state) {
state = (await job.getState()) as JobStatus;
this.jobStateCache.set(cacheKey, state);
}
}
const duration =
job.finishedOn && job.processedOn
? job.finishedOn - job.processedOn
: undefined;
// Normalize progress to number or object
let progress: number | object = 0;
if (typeof job.progress === "number") {
progress = job.progress;
} else if (typeof job.progress === "object" && job.progress !== null) {
progress = job.progress;
}
// Extract configured tag fields from job data
const tags = this.extractTags(job.data);
// Extract parent info if this job is part of a flow
let parent: { id: string; queueName: string } | undefined;
if (job.parent?.id) {
parent = {
id: job.parent.id,
queueName:
job.parent.queueKey?.split(":")[1] || job.parent.queueKey || "",
};
} else if (job.parentKey) {
// parentKey format: "bull:queueName:jobId"
const parts = job.parentKey.split(":");
if (parts.length >= 3) {
parent = {
id: parts[parts.length - 1] || "",
queueName: parts[parts.length - 2] || "",
};
}
}
return {
id: job.id || "",
name: job.name,
data: job.data,
opts: {
attempts: job.opts.attempts,
delay: job.opts.delay,
priority: job.opts.priority,
},
progress,
attemptsMade: job.attemptsMade,
processedOn: job.processedOn,
finishedOn: job.finishedOn,
timestamp: job.timestamp,
failedReason: job.failedReason,
stacktrace: job.stacktrace,
returnvalue: job.returnvalue,
status: state as JobStatus,
duration,
tags,
parent,
};
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Bulk Operations
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Retry multiple jobs across queues
* Processed in parallel for better performance
*/
async bulkRetry(
jobs: { queueName: string; jobId: string }[],
): Promise<{ success: number; failed: number }> {
const results = await Promise.allSettled(
jobs.map(async ({ queueName, jobId }) => {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error("Queue not found");
}
const job = await queue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.retry();
this.invalidateJobCache(queueName, jobId);
return { success: true };
}),
);
let success = 0;
let failed = 0;
for (const result of results) {
if (result.status === "fulfilled") {
success++;
} else {
failed++;
}
}
return { success, failed };
}
/**
* Delete multiple jobs across queues
* Processed in parallel for better performance
*/
async bulkDelete(
jobs: { queueName: string; jobId: string }[],
): Promise<{ success: number; failed: number }> {
const results = await Promise.allSettled(
jobs.map(async ({ queueName, jobId }) => {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error("Queue not found");
}
const job = await queue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.remove();
this.invalidateJobCache(queueName, jobId);
return { success: true };
}),
);
let success = 0;
let failed = 0;
for (const result of results) {
if (result.status === "fulfilled") {
success++;
} else {
failed++;
}
}
return { success, failed };
}
/**
* Promote multiple delayed jobs across queues (move to waiting)
* Processed in parallel for better performance
*/
async bulkPromote(
jobs: { queueName: string; jobId: string }[],
): Promise<{ success: number; failed: number }> {
const results = await Promise.allSettled(
jobs.map(async ({ queueName, jobId }) => {
const queue = this.queues.get(queueName);
if (!queue) {
throw new Error("Queue not found");
}
const job = await queue.getJob(jobId);
if (!job) {
throw new Error("Job not found");
}
await job.promote();
this.invalidateJobCache(queueName, jobId);
return { success: true };
}),
);
let success = 0;
let failed = 0;
for (const result of results) {
if (result.status === "fulfilled") {
success++;
} else {
failed++;
}
}
return { success, failed };
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Flow Operations
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Get all flows (jobs that have children or are part of a flow) - cached
* Optimized to focus on waiting-children type first and early exit
*/
async getFlows(limit = 50): Promise<FlowSummary[]> {
if (!this.flowProducer) {
return [];
}
return this.cached(`flows:${limit}`, this.CACHE_TTL.flows, async () => {
const queueEntries = Array.from(this.queues.entries());
// Check counts first to skip empty queues
const queueChecks = await Promise.all(
queueEntries.map(async ([queueName, queue]) => {
const counts = await this.getCachedJobCounts(queue);
const hasRelevantJobs =
(counts.waiting || 0) > 0 ||
(counts["waiting-children"] || 0) > 0 ||
(counts.active || 0) > 0;
return { queueName, queue, hasRelevantJobs };
}),
);
const relevantQueues = queueChecks.filter((q) => q.hasRelevantJobs);
if (relevantQueues.length === 0) {
return [];
}
// Focus on waiting-children first (most likely to be flows)
// Then check other types with reduced limits
const queueResults = await Promise.all(
relevantQueues.map(async ({ queueName, queue }) => {
try {
// Fetch waiting-children first (most likely flows) with higher limit
const waitingChildrenJobs = await queue.getJobs(
["waiting-children"],
0,
50,
);
// If we already have enough flows, skip other types
if (waitingChildrenJobs.length >= limit) {
return { queueName, jobs: waitingChildrenJobs };
}
// Fetch other types with reduced limits
const otherTypes = [
"waiting",
"active",
"completed",
"failed",
"delayed",
];
const otherJobArrays = await Promise.all(
otherTypes.map(async (type) => {
try {
return await queue.getJobs(type as any, 0, 30); // Reduced from 100
} catch {
return [];
}
}),
);
const allJobs = [...waitingChildrenJobs, ...otherJobArrays.flat()];
return { queueName, jobs: allJobs };
} catch {
return { queueName, jobs: [] };
}
}),
);
// Collect potential root jobs (no parent)
// Early exit when we have enough flows
const seenJobIds = new Set<string>();
const potentialRoots: { queueName: string; job: Job }[] = [];
for (const { queueName, jobs } of queueResults) {
// Early exit if we have enough flows
if (potentialRoots.length >= limit * 2) {
break;
}
for (const job of jobs) {
if (!job || !job.id) continue;
const jobKey = `${queueName}:${job.id}`;
if (seenJobIds.has(jobKey)) continue;
seenJobIds.add(jobKey);
// Check if this is a root job (has no parent)
const hasParent = !!job.parent || !!job.parentKey;
if (!hasParent) {
potentialRoots.push({ queueName, job });
// Early exit if we have enough potential roots
if (potentialRoots.length >= limit * 2) {
break;
}
}
}
}
// Check flows in parallel (batch to avoid overwhelming Redis)
const batchSize = 20;
const flows: FlowSummary[] = [];
for (
let i = 0;
i < potentialRoots.length && flows.length < limit;
i += batchSize
) {
const batch = potentialRoots.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(async ({ queueName, job }) => {
try {
const flowTree = await this.flowProducer!.getFlow({
id: job.id!,
queueName,
});
if (flowTree?.children && flowTree.children.length > 0) {
const stats = this.countFlowStats(flowTree);
const state = await job.getState();
return {
id: job.id!,
name: job.name,
queueName,
status: state as JobStatus,
totalJobs: stats.total,
completedJobs: stats.completed,
failedJobs: stats.failed,
timestamp: job.timestamp,
duration:
job.finishedOn && job.processedOn
? job.finishedOn - job.processedOn
: undefined,
} as FlowSummary;
}
} catch {
// Job might not have a flow, skip
}
return null;
}),
);
for (const result of batchResults) {
if (result && flows.length < limit) {
flows.push(result);
}
}
}
return flows.sort((a, b) => b.timestamp - a.timestamp);
});
}
/**
* Get a single flow tree by root job ID
*/
async getFlow(queueName: string, jobId: string): Promise<FlowNode | null> {
if (!this.flowProducer) {
return null;
}
try {
const flowTree = await this.flowProducer.getFlow({
id: jobId,
queueName,
});
if (!flowTree) {
return null;
}
return this.convertFlowTree(flowTree);
} catch {
return null;
}
}
/**
* Create a new flow
*/
async createFlow(request: CreateFlowRequest): Promise<{ id: string }> {
if (!this.flowProducer) {
throw new Error("FlowProducer not initialized");
}
const flowJob = this.buildFlowJob(request);
const result = await this.flowProducer.add(flowJob);
return { id: result.job.id || "" };
}
/**
* Build a FlowJob from CreateFlowRequest or CreateFlowChildRequest
*/
private buildFlowJob(
request: CreateFlowRequest | CreateFlowChildRequest,
): any {
const result: any = {
name: request.name,
queueName: request.queueName,
data: request.data || {},
};
if (request.children && request.children.length > 0) {
result.children = request.children.map((child) =>
this.buildFlowJob(child),
);
}
return result;
}
/**
* Convert BullMQ flow tree to our FlowNode structure
*/
private async convertFlowTree(tree: any): Promise<FlowNode> {
const job = tree.job;
const state = await job.getState();
const duration =
job.finishedOn && job.processedOn
? job.finishedOn - job.processedOn
: undefined;
const jobInfo: JobInfo = {
id: job.id || "",
name: job.name,
data: job.data,
opts: {
attempts: job.opts?.attempts,
delay: job.opts?.delay,
priority: job.opts?.priority,
},
progress:
typeof job.progress === "number"
? job.progress
: typeof job.progress === "object"
? job.progress
: 0,
attemptsMade: job.attemptsMade || 0,
processedOn: job.processedOn,
finishedOn: job.finishedOn,
timestamp: job.timestamp,
failedReason: job.failedReason,
stacktrace: job.stacktrace,
returnvalue: job.returnvalue,
status: state as JobStatus,
duration,
tags: this.extractTags(job.data),
};
const children: FlowNode[] = [];
if (tree.children && tree.children.length > 0) {
for (const child of tree.children) {
children.push(await this.convertFlowTree(child));
}
}
return {
job: jobInfo,
queueName: job.queueName || tree.queueName || "",
children: children.length > 0 ? children : undefined,
};
}
/**
* Count statistics for a flow tree
*/
private countFlowStats(tree: any): {
total: number;
completed: number;
failed: number;
} {
let total = 1;
let completed = 0;
let failed = 0;
// Check current job status (synchronously from available data)
const job = tree.job;
if (job.finishedOn && !job.failedReason) {
completed = 1;
} else if (job.failedReason) {
failed = 1;
}
if (tree.children) {
for (const child of tree.children) {
const childStats = this.countFlowStats(child);
total += childStats.total;
completed += childStats.completed;
failed += childStats.failed;
}
}
return { total, completed, failed };
}
}
|